在 Python 中使用 OpenCV 在不存在的文件夹中创建文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17513686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a file in a non-existing folder using OpenCV in Python
提问by rlvamsi
i am trying to create an image file using opencv in python. when i am creating it in same folder file is created
我正在尝试在 python 中使用 opencv 创建一个图像文件。当我在同一个文件夹中创建它时,文件被创建
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.
我什至尝试给出绝对路径。我在 Windows 中使用 python2.7。
采纳答案by Aurelius
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:
cv2.imwrite()
如果目录不存在,则不会在另一个目录中写入图像。在尝试写入之前,您首先需要创建目录:
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)