在Python中使用OpenCV在不存在的文件夹中创建文件 [英] Creating a file in a non-existing folder using OpenCV in Python
问题描述
我正在尝试使用python中的opencv创建图像文件. 当我在同一文件夹中创建它时
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??
我什至尝试给出绝对路径. 我在Windows中使用python2.7.
i even tried giving absolute path. i am using python2.7 in windows.
推荐答案
cv2.imwrite()
如果该目录不存在,则不会在另一个目录中写入映像.在尝试写入目录之前,您首先需要创建目录:
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)
这篇关于在Python中使用OpenCV在不存在的文件夹中创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!