opencv/samples/python/tutorial_code/imgcodecs/animations.py
Suleyman TURKMEN d9a139f9e8
Merge pull request #25608 from sturkmen72:animated_webp_support
Animated WebP Support #25608

related issues #24855 #22569 

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2024-12-20 13:06:28 +03:00

53 lines
1.6 KiB
Python

import cv2 as cv
import numpy as np
def main(filename):
## [write_animation]
if filename == "animated_image.webp":
# Create an Animation instance to save
animation_to_save = cv.Animation()
# Generate a base image with a specific color
image = np.full((128, 256, 4), (150, 150, 150, 255), dtype=np.uint8)
duration = 200
frames = []
durations = []
# Populate frames and durations in the Animation object
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
# Write the animation to file
cv.imwriteanimation(filename, animation_to_save, [cv.IMWRITE_WEBP_QUALITY, 100])
## [write_animation]
## [init_animation]
animation = cv.Animation()
## [init_animation]
## [read_animation]
success, animation = cv.imreadanimation(filename)
if not success:
print("Failed to load animation frames")
return
## [read_animation]
## [show_animation]
while True:
for i, frame in enumerate(animation.frames):
cv.imshow("Animation", frame)
key_code = cv.waitKey(animation.durations[i])
if key_code == 27: # Exit if 'Esc' key is pressed
return
## [show_animation]
if __name__ == "__main__":
import sys
main(sys.argv[1] if len(sys.argv) > 1 else "animated_image.webp")