FileNotFoundError: [Errno 2] No such file or directory: 'frame0.png' but actually has

FileNotFoundError: [Errno 2] No such file or directory: 'frame0.png' but actually has

关于路径问题,我和许多 post 有类似的问题,但我找不到任何解决方案来解决我的问题

所以首先,我有一个功能,我可以创建一个目录来存储从视频中提取的所有帧

def extract_frame(video,folder):

    os.mkdir(folder)
    vidcap = cv2.VideoCapture(video)
    success,image = vidcap.read()
    fps = vidcap.get(cv2.CAP_PROP_FPS)
    count = 0
    success = True
    while success:  #os.path.join(pathOut,(name+'.png'))
      cv2.imwrite(os.path.join(folder,"frame%d.png" % count), image)         
      success,image = vidcap.read()
      print('Read a new frame: ', success) 
      count += 1

效果很好,我希望处理所有帧,所以我写了

def rm_green(pathOut):   

    for f in os.listdir(pathOut):   
        if f[-3:] == "png":         
            name, ext = os.path.splitext(f)
            im = Image.open(f)
            im = im.convert('RGBA')
            .
            .
            . ## and some other line of code blah blah

然后我终于调用了函数:

extract_frame('vid.mp4', 'test1')
pathIn='./test1/'
rm_green(pathIn)

从这里开始,函数 extract_frame() 运行良好,它创建了一个名为 'test1' 的文件夹,其中包含所有帧。但是有错误

File "C:\Users\DELL\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)

File "C:\Users\DELL\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/DELL/Desktop/Senior/video/bg/use this/extract-remove-green-combinevid.py", line 113, in <module>
rm_green(pathIn)

File "C:/Users/DELL/Desktop/Senior/video/bg/use this/extract-remove-green-combinevid.py", line 61, in rm_green
im = Image.open(f)

FileNotFoundError: [Errno 2] No such file or directory: 'frame0.png'

我不知道为什么会这样,因为文件夹 test1 中有帧。我写路径的方式有什么问题吗?它怎么会发生,因为它读取了 test1 文件夹中的 'frame0.png'?或者此错误与 PIL 库中的 Image.open(f) 有关?

谢谢

编辑: 代码来自名为 extract-remove-green.. 的 py 文件。 >> 这个 os.listdir() 工作正常吗?

我看到您正在尝试直接从循环变量中使用 f。但这只是文件名而不是文件路径。您可能必须执行 os.abspath(f) 以获得文件的完整路径,然后 运行 对其执行所需的操作。

for f in os.listdir(pathOut):
    file_path = os.path.abspath(os.path.join(pathOut, f))
    if f[-3:] == "png":         
        name, ext = os.path.splitext(f)
        im = Image.open(file_path)
        im = im.convert('RGBA')

希望对您有所帮助。谢谢

这里有一个提示,如何获取文件目录的完整路径:

import path
script_dir = path.dirname(path.abspath(__file__))

然后您可以使用连接或连接来获取您的文件或子目录的完整路径:

file_path = script_dir.join("\the_name_of_file_or_directory") 
# file_path  = script_dir + "\the_name_of_file_or_directory"