我有一个根文件夹,它包含多个文件夹,其中一些包含png,另一些包含子文件夹和png。
我的代码:
import os
import cv2
root = r'C:UserssboroghinaDocuments_projectsjson_compare'
for videopath, videodirs, videofiles in os.walk(root, topdown=False):
for videoname in videodirs:
if len(videoname) > 40:
video_name = str(videoname) + '.avi'
for path, dirs, files in os.walk(root, topdown=False):
image_folder = path
images = [f for f in os.listdir(image_folder) if f.endswith('.png')]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 30, (width, height))
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()
我收到这个错误:
Traceback (most recent call last):
File "C:UserssboroghinaDocuments_projectsgenerate_annotation_imagestest2.py", line 20, in <module>
frame = cv2.imread(os.path.join(image_folder, images[0]))
IndexError: list index out of range
我不明白为什么它会给我这个错误。
您定义了images
变量,如下所示:
images = [f for f in os.listdir(image_folder) if f.endswith('.png')]
之后,在没有任何验证的情况下,你做了:
images[0]
现在,当images
是一个空列表时,这可能会导致问题,这意味着os.listdir(image_folder)
中列出的文件都没有以".png'
结尾。
只需更改此代码块:
for path, dirs, files in os.walk(root, topdown=False):
image_folder = path
images = [f for f in os.listdir(image_folder) if f.endswith('.png')]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 30, (width, height))
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()
至:
for path, dirs, files in os.walk(root, topdown=False):
image_folder = path
images = [f for f in os.listdir(image_folder) if f.endswith('.png')]
if images: # Validation
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 30, (width, height))
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows() # Unindented
video.release()
注意,我也曾经取消过这些行:
cv2.destroyAllWindows()
video.release()
使得CCD_ 5对象直到写入所有帧之后才被释放