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

亡梦爱人 提交于 2020-01-01 09:35:02

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/17513686/creating-a-file-in-a-non-existing-folder-using-opencv-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!