본문 바로가기
Python

[Python] gif 이미지 opencv 로 로드하기 cv2

by bryan.oh 2020. 5. 18.
반응형

python opencv
cv2 imread gif

 

gif 를 

cv2.imread('./test.gif')

이렇게 읽으면 오류가 납니다.

gif 는 여러개의 이미지가 존재하는 video 같은거라고 보면 됩니다.

frame 을 읽어와야죠.

 

이미지가 gif 형식이면 첫번째 frame 만 읽어오는 함수입니다.

	import cv2
	import numpy as np
    
	def loadImageFromPath(imgPath):
        try:
            # gif 처리
            if str(imgPath).lower().endswith('.gif'):
                gif = cv2.VideoCapture(imgPath)
                ret, frame = gif.read()  # ret=True if it finds a frame else False.
                if ret:
                    return frame
            else:
                return cv2.imread(imgPath)
        except Exception as e:
            print(e)
            return None

모든 frame 을 읽어오려면

ret, frame = gif.read() 

에서 ret 가 True 일동안 계속해서 while 문 돌면 되겠지요.

gif = cv2.VideoCapture(imgPath)
ret, frame = gif.read()  # ret=True if it finds a frame else False.
while ret:
	# something to do 'frame'
    # ...
    # 다음 frame 읽음
    ret, frame = gif.read()

 

저는 opencv 만 사용하려다 보니 위 처럼 써놨는데요.

다른 방법도 많이 있습니다. 아래 참고하세요~ 

 

 

<참고>

1. PIL 사용하는 방법

from PIL import Image, ImageSequence

im = Image.open("animation.gif")

index = 1
for frame in ImageSequence.Iterator(im):
    frame.save("frame%d.png" % index)
    index += 1

2. imgpy 라이브러리 사용

https://pypi.org/project/imgpy/

# 설치
$ pip3 install imgpy

# 사용
from imgpy import Img


# Crop image
with Img(fp='test.gif') as im:
    im.crop(box=(10, 10, 110, 110))
    im.save(fp='crop.gif')

# Create thumbnail image
with Img(fp='test.gif') as im:
    im.thumbnail(size=(100, 100))
    im.save(fp='thumb.gif')

# Save 10 random GIF frames
with Img(fp='test.gif') as im:
    im.load(limit=10, first=False)
    im.save(fp='random.gif')

 

728x90
반응형

댓글