如何使用 opencv 读取文件夹中的第一张图像 (python)

How to read the first image in folder using opencv (python)

我正在使用以下代码读取和计算文件夹中连续图像之间的差异:

def cal_for_frames(video_path):
    frames = glob(os.path.join(video_path, '*.jpg'))
    frames.sort()


    diff = []
    prev = cv2.imread(frames[0])
    prev = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
    print(prev.dtype, prev.shape)
    for i, frame_curr in enumerate(frames):
        curr = cv2.imread(frame_curr)
        curr = cv2.cvtColor(curr, cv2.COLOR_BGR2GRAY)
        print(curr.dtype, curr.shape)
        tmp_diff = compute_DIFF(prev, curr)
        diff.append(tmp_diff)
        prev = curr
    
    return diff

现在我希望我的 prev 始终是文件夹中的第一张图片(即保持不变)。我需要对 prev = cv2.imread(frames[0]) 进行哪些更改才能执行此操作?其中 frame000001 是文件夹中的第一张图像。

只需删除 for-loop 的最后一行:prev = currprev = cv2.imread(frames[0])

但您可以加快 for-loop。如果 print 功能不是关键,那么你可以这样做:

diff = [compute_DIFF(prev, cv2.cvtColor(cv2.imread(frame_curr), cv2.COLOR_BGR2GRAY)) for i, frame_curr in enumerate(frames)]

代码:


def cal_for_frames(video_path):
    frames = glob(os.path.join(video_path, '*.jpg')).sort()
    prev = cv2.cvtColor(cv2.imread(frames[0]), cv2.COLOR_BGR2GRAY)
    print(prev.dtype, prev.shape)

    diff = [compute_DIFF(prev, cv2.cvtColor(cv2.imread(frame_curr), cv2.COLOR_BGR2GRAY)) for i, frame_curr in enumerate(frames)]

    return diff