首页 > 解决方案 > FileNotFoundError: [Errno 2] No such file or directory: 'frame0.png' 但实际上有

问题描述

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

所以首先,我有一个函数,我在其中创建一个目录,该目录将存储从视频中提取的所有帧

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) 有关?

谢谢

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

标签: pythonpython-imaging-libraryfile-not-found

解决方案


我看到您正在尝试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')

希望这对您有所帮助。谢谢。


推荐阅读