Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a file in a non-existing folder using OpenCV in Python

i am trying to create an image file using opencv in python. when i am creating it in same folder file is created

          face_file_name = "te.jpg"
          cv2.imwrite(face_file_name, image)

but when i am trying to create it in another folder like

          face_file_name = "test\te.jpg"
          cv2.imwrite(face_file_name, image)

file is not created. can someone explain the reasons??

i even tried giving absolute path. i am using python2.7 in windows.

like image 925
rlvamsi Avatar asked Jul 07 '13 15:07

rlvamsi


People also ask

How do you create a file and the directory if it doesn't exist in python?

#python program to check if a directory exists import os path = "pythonprog" # Check whether the specified path exists or not isExist = os. path. exists(path) if not isExist: # Create a new directory because it does not exist os. makedirs(path) print("The new directory is created!")

How do you create a file and directory in python?

To create a new directory, you use os. mkdir() function. And you should always check if a directory exists first before creating a new directory. The following example creates a new directory called python under the c:\temp directory.


1 Answers

cv2.imwrite() will not write an image in another directory if the directory does not exist. You first need to create the directory before attempting to write to it:

import os
dirname = 'test'
os.mkdir(dirname)

From here, you can either write to the directory without changing your working directory:

cv2.imwrite(os.path.join(dirname, face_file_name), image)

Or change your working directory and omit the directory prefix, depending on your needs:

os.chdir(dirname)
cv2.imwrite(face_file_name, image)
like image 73
Aurelius Avatar answered Oct 17 '22 17:10

Aurelius