13

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.

4
  • 2
    What about escape characters? What if you tried "test\\te.jpg"? Commented Jul 7, 2013 at 15:55
  • thanq chrisaycock forgot abt that Commented Jul 7, 2013 at 16:07
  • and its only creating if folder already exits wht if i want to create a new folder and create the file in it Commented Jul 7, 2013 at 16:10
  • any errors? do you have write access to the folder? Commented Jul 7, 2013 at 17:06

1 Answer 1

48

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Took me a long time before I realised I had to create the folder, couldn't figure out why my images wouldn't be saved :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.