How can I extract frames from gif and further convert the frame into grayscale?

190 Views Asked by At

So, I'm working on this task I was given where I should be able to compare two image files and state how similar they are. But it should work with all file formats like jpg, png, gif etc with files of different sizes.

I am using the Structural Similarity Index method to do this task. The program I've worked on till now accommodates all required file formats except gif and to work with gif I need to extract a frame from the gif, convert it to grayscale and resize etc After extracting the frames I need to save it locally on the disk before I can convert it into grayscale. Is there a way I can extract the frame and directly convert into grayscale without saving the frame locally?

1

There are 1 best solutions below

2
ShadowCrafter_01 On

I don't know which libraries you use so I just went with opencv. The code below just loops over all the frames in a gif file, converts them to grayscale, displays them and waits for the user to press a key to display the next frame.

import cv2


gif = cv2.VideoCapture('gif.gif')
frames = []
ret, frame = gif.read()  # ret=True if it finds a frame else False.
while ret:
    # read next frame
    ret, frame = gif.read()
    if not ret:
        break

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow("image", frame)
    cv2.waitKey(0)

cv2.destroyAllWindows()

I think you should be able to adapt this code for your usecase.