How to save to a specific directory (python)?

Asked

Viewed 747 times

0

Hello. I would like to know how to create a folder every time the program is run and save to a specific location.

Currently it saves the file where the code is.

This is my current code:

import cv2
from datetime import datetime
import numpy as up

def main(args):

    camera_port1 = 0     
    nFrames = 30

    camera1 = cv2.VideoCapture(camera_port1)
    data = datetime.now().strftime("%Y-%m-%d__%H-%M-%S")

   file1 =("camera_1_{}.png".format(data))

    print ("Digite <ESC> para sair / <s> para Salvar")   

    emLoop= True

    while(emLoop):

        retval1, img1 = camera1.read()
        cv2.imshow('Foto1',img1)

        k = cv2.waitKey(100)

        if k == 27:
            emLoop= False

        elif k == ord('s'):
            cv2.imwrite(file1,img1)
            emLoop= False

    cv2.destroyAllWindows()
    camera1.release()

    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))
  • Change the file1, to a directory, for example: C:\\Users\\nome_do_usuario\\Envs\\ambiente_python\\Lib\\site-packages\\cv2\\data\\imagem.png plus the file name. The code file1 =("camera_1_{}.png".format(data)). Or use libraries to find a directory os.path.dirname(cv2.__file__). Finally, read about the library the

  • Windows or Unix?

1 answer

0

Just use the OS module is very easy:

notice that you currently save like this:

elif k == ord('s'):
    cv2.imwrite(file1,img1)
    emLoop= False

we can add the following procedure:

elif k == ord('s'):
    if os.path.isdir('C:/caminho/do/diretorio'):
         cv2.imwrite('C:/caminho/do/diretorio/{}'.format(file1),img1)
    else:
        os.makedirs('C:/caminho/do/diretorio')
        cv2.imwrite('C:/caminho/do/diretorio/{}'.format(file1),img1

    emLoop= False

With this it will check if the directory exists. if it exists it is saved in it. if it does not exist it will create it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.