This activity will help you learn how to create simple animations
using for
loops, and the
show
function. You will also explore using drawing elements to create animations. (See the Drawing
Shapes activity and the Introduction to Pictures
reading for a refresher on the drawing functions.)
from PIL import Image, ImageDraw
import cv2
import numpy as np
import glob
import math
The comments in the function describe what it is doing.def moveBox(): # Create empty array to hold the images img_array = [] # Create a new image to be used as the background newImage = Image.new('RGB',(200,200),'yellow') # Create a box that will be the moving object box = Image.new('RGB',(10,10),'red') # Set up the loop to go across the image, stepping by 10 for x in range(0,newImage.width,10): # refresh the background image newImage = Image.new('RGB',(200,200),'yellow') # paste the box into the image newImage.paste(box, (x,10)) # show the image newImage.show() # print an empty line to separate the images print() # add the image to an array img_array.append(newImage) #return the array of images return img_array
def writeArrayToJPGS(myArray, path, picName): for i in range(len(myArray)): myArray[i].save(path+"/"+picName+str(i)+".jpg","JPEG")
Boxes
on your Google drive.
This will save the array of images that gets produced in themyBoxes = moveBox() boxPath = '/drive/MyDrive/Colab Notebooks/Boxes' writeArrayToJPGS(myBoxes, boxPath, 'boxPic')
moveBox
function
into a variable. The path of the new folder you created on your Google drive gets saved
into the boxPath
variable, and then the writeArrayToJPGS
function
will save all of those images into your folder.
jpg
files and write them to an
mp4
file. The following function will do this for us:
Copy this file and then test it by adding a statement like the following after the code used for writing the array images to jpeg files:def convertPicsToMovie(path, videoname): img_array = [] for filename in glob.glob(path+'/*.jpg'): img = cv2.imread(filename) height, width, layers = img.shape size = (width,height) img_array.append(img) out = cv2.VideoWriter(path+'/'+videoname,cv2.VideoWriter_fourcc(*'MP4V'), 15, size) for i in range(len(img_array)): out.write(img_array[i]) out.release()
convertPicsToMovie(boxPath, 'box.mp4')
for
loop.)
def movingRectangles(): img_array = [] pict = Image.new('RGB',(200,200)) box = Image.new('RGB',(15,15), 'blue') pinkBox = Image.new('RGB', (20,20),'pink') for y in range(pict.height//4): pict = Image.new('RGB',(200,200)) pict.paste(box, (y*5, y*5)) pinkx = 100 + int(10*math.sin(y)) pinky = 4*y + int(10*math.cos(y)) pict.paste(pinkBox, (pinkx, pinky)) pict.show() print() img_array.append(pict) return img_array