animations.cpp 1.5 KB

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