0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenCVを使ってGIFファイルを読み込む方法

0
Posted at

Introduction

パテントの問題があったためか、以前は読み込むことができなかったGIFファイルがOpenCVで使えるようになりました!!

Code

cv2.imreadanimation にgifファイルを読み込むと動画みたいに複数のフレームとして出力されます。

import argparse
from pathlib import Path

import cv2


def valid_filepath(src: Path):
    if not src.exists():
        print("[error]:ファイルパスが存在しません")
        return False

    if not src.is_file():
        print("[error]:ファイルではありません")
        return False

    if not src.suffix in [".png", ".jpg", ".jpeg", ".gif"]:
        print("[error]:ファイルが画像ではありません")
        return False
    return True


def exec():
    parser = argparse.ArgumentParser()
    parser.add_argument("src_img", type=str)
    parser.add_argument("repeat", type=int, default=5)

    args = parser.parse_args()

    input_path = Path(args.src_img)
    if not valid_filepath(input_path):
        return False

    output_folder = Path("OUTPUT")
    if not output_folder.exists():
        output_folder.mkdir()

    ret, srcFrames = cv2.imreadanimation(input_path)

    for i in range(args.repeat):
        for frame in srcFrames.frames:
            cv2.imshow("GIF", frame)
            cv2.waitKey(30)

    cv2.destroyAllWindows()

if __name__ == "__main__":
    exec()

Consequence

python gif.py cat_meme.gif 3

と実行するとGIFファイルが再生されます。

output-palette-none.gif

Reference

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?