Python中每次保存的文件命名计数

时间:2017-11-10 06:48:02

标签: python linux macos python-2.7 rename

我想知道如何告诉我的py脚本在循环中重命名每个保存的图像,而不是覆盖它们。正如您所看到的,它每隔30秒就会保存为image_01.png。

import time
import cv2
import sys
import sched, time

try:
    def DoWork():
            print('Capturing a Picture')
            camera_port = 0
            camera = cv2.VideoCapture(camera_port)
            time.sleep(0.1)  
            return_value, image = camera.read()
            cv2.imwrite("/Users/pnovak/Desktop/image_01.png", image)
            del(camera)   
            def countdown(t):
                while t:
                    mins, secs = divmod(t, 60)
                    timeformat = '{:02d}:{:02d}'.format(mins, secs)
                    sys.stdout.write('Next capture in '+timeformat+'\r')
                    sys.stdout.flush()
                    time.sleep(1)
                    t -= 1
                pass
            countdown(30)
            print
    while True:
            DoWork()
except KeyboardInterrupt:
    print
    print('User CTRL+C')
    sys.exit(0)

1 个答案:

答案 0 :(得分:1)

试试这个:

import time
import cv2
import sys
import sched, time

try:
    def DoWork(get_name):
            print('Capturing a Picture')
            camera_port = 0
            camera = cv2.VideoCapture(camera_port)
            time.sleep(0.1)  
            return_value, image = camera.read()
            file_name = "/Users/pnovak/Desktop/image_{0}.png".format(get_name) # new line
            cv2.imwrite(file_name, image)
            del(camera)   
            def countdown(t):
                while t:
                    mins, secs = divmod(t, 60)
                    timeformat = '{:02d}:{:02d}'.format(mins, secs)
                    sys.stdout.write('Next capture in '+timeformat+'\r')
                    sys.stdout.flush()
                    time.sleep(1)
                    t -= 1
                pass
            countdown(30)
            print
    counter = 0 # new line
    while True:
            DoWork(counter)
            counter = counter + 1 # new line
except KeyboardInterrupt:
    print
    print('User CTRL+C')
    sys.exit(0)