| |
| Original author | Suleyman Turkmen (with help of ChatGPT) |
| Compatibility | OpenCV >= 4.11 |
Goal
In this tutorial, you will learn how to:
Source Code
C++
- Downloadable code: Click here
- Code at a glance:
#include <iostream>
int main(
int argc,
const char** argv )
{
std::string filename = argc > 1 ? argv[1] : "animated_image.webp";
if (argc == 1)
{
int duration = 200;
for (int i = 0; i < 10; ++i) {
animation_to_save.
frames.push_back(image.clone());
putText(animation_to_save.
frames[i], format(
"Frame %d", i),
Point(30, 80), FONT_HERSHEY_SIMPLEX, 1.5,
Scalar(255, 100, 0, 255), 2);
animation_to_save.
durations.push_back(duration);
}
imwriteanimation("animated_image.webp", animation_to_save, { IMWRITE_WEBP_QUALITY, 100 });
}
bool success = imreadanimation(filename, animation);
if (!success) {
std::cerr << "Failed to load animation frames\n";
return -1;
}
while (true)
for (
size_t i = 0; i < animation.
frames.size(); ++i) {
if (key_code == 27)
exit(0);
}
return 0;
}
n-dimensional dense array class
Definition mat.hpp:839
#define CV_8UC4
Definition interface.h:91
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
int waitKey(int delay=0)
Waits for a pressed key.
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3
Represents an animation with multiple frames. The Animation struct is designed to store and manage da...
Definition imgcodecs.hpp:286
std::vector< int > durations
Duration for each frame in milliseconds.
Definition imgcodecs.hpp:302
std::vector< Mat > frames
Vector of frames, where each Mat represents a single frame.
Definition imgcodecs.hpp:304
Python
- Downloadable code: Click here
- Code at a glance:
import cv2 as cv
import numpy as np
if filename == "animated_image.webp":
image = np.full((128, 256, 4), (150, 150, 150, 255), dtype=np.uint8)
duration = 200
frames = []
durations = []
for i in range(10):
frame = image.copy()
cv.putText(frame, f
"Frame {i}", (30, 80), cv.FONT_HERSHEY_SIMPLEX, 1.5, (255, 100, 0, 255), 2)
frames.append(frame)
durations.append(duration)
animation_to_save.frames = frames
animation_to_save.durations = durations
if not success:
print("Failed to load animation frames")
return
while True:
for i, frame in enumerate(animation.frames):
if key_code == 27:
return
if __name__ == "__main__":
import sys
main(sys.argv[1]
if len(sys.argv) > 1
else "animated_image.webp")
bool imwriteanimation(const String &filename, const Animation &animation, const std::vector< int > ¶ms=std::vector< int >())
Saves an Animation to a specified file.
bool imreadanimation(const String &filename, Animation &animation, int start=0, int count=INT16_MAX)
Loads frames from an animated image file into an Animation structure.
void putText(InputOutputArray img, const String &text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=LINE_8, bool bottomLeftOrigin=false)
Draws a text string.
Explanation
Initializing the Animation Structure
Initialize a cv::Animation structure to hold the frames from the animated image file.
C++
Python
Loading Frames
Use cv::imreadanimation to load frames from the specified file. Here, we load all frames from an animated WebP image.
C++
if (!success) {
std::cerr << "Failed to load animation frames\n";
return -1;
}
Python
if not success:
print("Failed to load animation frames")
return
Displaying Frames
Each frame in the animation.frames vector can be displayed as a standalone image. This loop iterates through each frame, displaying it in a window with a short delay to simulate the animation.
Note: Frame durations in cv::Animation are expressed in milliseconds. When displaying frames manually using cv::waitKey, make sure to use the corresponding duration value to preserve the original animation timing.
C++
while (true)
for (
size_t i = 0; i < animation.
frames.size(); ++i) {
if (key_code == 27)
exit(0);
}
Python
while True:
for i, frame in enumerate(animation.frames):
if key_code == 27:
return
Saving Animation
C++
if (argc == 1)
{
int duration = 200;
for (int i = 0; i < 10; ++i) {
animation_to_save.
frames.push_back(image.clone());
putText(animation_to_save.
frames[i],
format(
"Frame %d", i),
Point(30, 80), FONT_HERSHEY_SIMPLEX, 1.5,
Scalar(255, 100, 0, 255), 2);
animation_to_save.
durations.push_back(duration);
}
}
Python
if filename == "animated_image.webp":
image = np.full((128, 256, 4), (150, 150, 150, 255), dtype=np.uint8)
duration = 200
frames = []
durations = []
for i in range(10):
frame = image.copy()
cv.putText(frame, f
"Frame {i}", (30, 80), cv.FONT_HERSHEY_SIMPLEX, 1.5, (255, 100, 0, 255), 2)
frames.append(frame)
durations.append(duration)
animation_to_save.frames = frames
animation_to_save.durations = durations
Summary
The cv::imreadanimation and cv::imwriteanimation functions make it easy to work with animated image files by loading frames into a cv::Animation structure, allowing frame-by-frame processing. With these functions, you can load, process, and save frames from animated image files like GIF, AVIF, APNG, and WebP.