0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! removing prev=curr did the trick. One more question, I am trying to save the images with "frame{%06d}.jpg".format(i) but I get a KeyError: '%06d'. It works fine when when I use "frame{}.jpg".format(i), I'd like to know what I am doing wrong, thanks.
Using "frame{%06d}.jpg".format(i) worked in the past, don't know why it doesn't work now.
I got it to work. I changed "frame{%06d}.jpg".format(i) to "frame{:06d}.jpg".format(i). Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.