变量不递增 [英] Variables not incrementing

查看:60
本文介绍了变量不递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在使用树莓派并尝试制作安全摄像头设备.我正在尝试对拍摄的每张照片进行编目,每张照片都有一个新的 .jpg 文件,我认为该部分已删除,但用于命名每张照片的变量不会增加.所以我有一个文件,每张照片都会被替换.我非常非常困惑.这是代码,任何帮助表示赞赏.

So, I'm using a raspberry pi and trying to make a security camera device. I'm trying to catalog every photo taken, with a new .jpg file for each pic and i think have that part down but the variable using to name each photo wont increment. So I have one file that keeps getting replaced with each picture taken. I'm very very confused. Here's code, any help is appreciated.

#defines camera function
def camera(pic_num):
    with picamera.PiCamera() as camera:
        camera.start_preview()
        time.sleep(5)
        pic_num += 1
        camera.capture('/home/pi/locker_photos/' + str(pic_num) + '.jpg')
        print (pic_num)
        camera.stop_preview()

推荐答案

发生这种情况是因为 pic_num 被分配为 camera<中的局部变量/代码> 功能.解决问题的最简单方法是从调用 camera 的任何位置在 camera 函数之外增加 pic_num.

This is happening because pic_num is being assigned as a local variable inside your camera function. The easiest way to resolve your issue would be to increment pic_num outside of the camera function from wherever you are calling camera.

如果可以,这里有一种更智能的命名方式,无需跟踪计数器:

If I may, here's a smarter way of doing this naming that doesn't involve keeping track of a counter:

#defines camera function
def camera():
    PHOTOS_DIR = '/home/pi/locker_photos/'
    with picamera.PiCamera() as camera:
        camera.start_preview()
        time.sleep(5)
        # Get the next highest number from the files that already exist
        pic_num = max(int(os.path.splitext(f)[0]) for f in os.listdir(PHOTOS_DIR)) + 1
        camera.capture(PHOTOS_DIR + str(pic_num) + '.jpg')
        print (pic_num)
        camera.stop_preview()

这篇关于变量不递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆