|
| 1 | +#------------------------------------------------------------------------------- |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | +# |
| 4 | +# Copyright (c) 2025 SparkFun Electronics |
| 5 | +#------------------------------------------------------------------------------- |
| 6 | +# ex07_animation.py |
| 7 | +# |
| 8 | +# This example demonstrates how to play an animation using a series of frames |
| 9 | +# stored in a single image file. It assumes full 320x240 frames are stacked |
| 10 | +# vertically in the image, and the animation plays by displaying each frame in |
| 11 | +# sequence. This can be the basis for things like sprite sheets, where smaller |
| 12 | +# icons or characters are stored in a single image and displayed as needed. |
| 13 | +#------------------------------------------------------------------------------- |
| 14 | + |
| 15 | +# Import OpenCV and hardware initialization module |
| 16 | +import cv2 as cv |
| 17 | +from cv2_hardware_init import * |
| 18 | + |
| 19 | +# Load an animation sheet image that contains multiple frames of an animation |
| 20 | +animation_sheet = cv.imread("opencv-examples/images/animation_sheet.png") |
| 21 | + |
| 22 | +# This example assumes the image has full 320x240 frames stacked vertically |
| 23 | +frame_height = 240 |
| 24 | + |
| 25 | +# Calculate the number of frames in the sheet by dividing the sheet height by |
| 26 | +# the frame height |
| 27 | +frame_num = animation_sheet.shape[0] // frame_height |
| 28 | + |
| 29 | +# Initialize variables to keep track of the current row in the sheet and the |
| 30 | +# direction of animation playback (up or down) |
| 31 | +row_index = 0 |
| 32 | +direction = 1 |
| 33 | + |
| 34 | +# Prompt the user to press a key to continue |
| 35 | +print("Press any key to continue") |
| 36 | + |
| 37 | +# Loop to continuously play the animation |
| 38 | +while True: |
| 39 | + # Calculate the starting and ending pixel row for the current frame |
| 40 | + row_start_px = row_index * frame_height |
| 41 | + row_end_px = row_start_px + frame_height |
| 42 | + cv.imshow(display, animation_sheet[row_start_px:row_end_px, :]) |
| 43 | + |
| 44 | + # Update the row index based on the direction of playback |
| 45 | + row_index += direction |
| 46 | + |
| 47 | + # If we reach the end of the sheet, reverse the direction |
| 48 | + if row_index == frame_num-1: |
| 49 | + direction = -1 |
| 50 | + elif row_index == 0: |
| 51 | + direction = 1 |
| 52 | + |
| 53 | + # Check for key presses. If you want the animation to play at a specific |
| 54 | + # frame rate, you can change the wait time to slow it down. This example |
| 55 | + # plays the animation as fast as possible, which is often needed to look |
| 56 | + # smooth in MicroPython |
| 57 | + key = cv.waitKey(1) |
| 58 | + |
| 59 | + # If any key is pressed, exit the loop |
| 60 | + if key != -1: |
| 61 | + break |
0 commit comments