Search code examples
python-3.xopencvimage-processingglobimread

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


I am using the following code to read and compute difference between consecutive images in a folder:

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

Now I want my prev to always be the first image in the folder (i.e., to be constant). What changes do I need to make to prev = cv2.imread(frames[0]) to do this? where frame000001 is the first image in the folder.


Solution

  • Just remove the for-loop's last line: prev = curr and prev = cv2.imread(frames[0]).

    But you can speed up your for-loop. If print function is not crucial, then you can do:

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

    Code:


    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