samples/cpp/tutorial_code/imgcodecs/animations.cpp#

An example to show usage of cv::imreadanimation and cv::imwriteanimation functions. Check the corresponding tutorial for more details

 1#include <opencv2/highgui.hpp>
 2#include <opencv2/imgcodecs.hpp>
 3#include <opencv2/imgproc.hpp>
 4#include <iostream>
 5
 6using namespace cv;
 7
 8int main( int argc, const char** argv )
 9{
10    std::string filename = argc > 1 ? argv[1] : "animated_image.webp";
11
12    //! [write_animation]
13    if (argc == 1)
14    {
15        Animation animation_to_save;
16        Mat image(128, 256, CV_8UC4, Scalar(150, 150, 150, 255));
17        int duration = 200;
18
19        for (int i = 0; i < 10; ++i) {
20            animation_to_save.frames.push_back(image.clone());
21            putText(animation_to_save.frames[i], format("Frame %d", i), Point(30, 80), FONT_HERSHEY_SIMPLEX, 1.5, Scalar(255, 100, 0, 255), 2);
22            animation_to_save.durations.push_back(duration);
23        }
24        imwriteanimation("animated_image.webp", animation_to_save, { IMWRITE_WEBP_QUALITY, 100 });
25    }
26    //! [write_animation]
27
28    //! [init_animation]
29    Animation animation;
30    //! [init_animation]
31
32    //! [read_animation]
33    bool success = imreadanimation(filename, animation);
34    if (!success) {
35        std::cerr << "Failed to load animation frames\n";
36        return -1;
37    }
38    //! [read_animation]
39
40    //! [show_animation]
41    while (true)
42    for (size_t i = 0; i < animation.frames.size(); ++i) {
43        imshow("Animation", animation.frames[i]);
44        int key_code = waitKey(animation.durations[i]); // Delay between frames
45        if (key_code == 27)
46            exit(0);
47    }
48    //! [show_animation]
49
50    return 0;
51}