In-Class Activity: Using Loops to Create Simple Animations

 


Introduction

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.)



Getting Started

  1. Create a new notebook in Google Colab.
  2. Add a new Text Cell with your name, the date, and a description of the activity.
  3. In a new Code Cell, copy the code from a previous notebook to Mount yoiur Google drive.
  4. In a new Code Cell, add the following import statements:
    from PIL import Image, ImageDraw
    import cv2
    import numpy as np
    import glob
    import math

Moving in Straight Lines

  1. The following function moves a red box across a horizontal line. (You may want to experiment with different horizontal lines.) Copy it and call it to see how it works.
            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
        
    The comments in the function describe what it is doing.
  2. Optional: Write a function similar to the one above, but pass the row number and the color for the box as parameters rather than constants.
  3. Write a function similar to the one above that moves the box along a vertical line instead of a horizontal line.
  4. Write a function that moves a box around the perimeter of the canvas. It should move across the top, down the right side, back across the bottom, and then up the left side. (Note: remember you can use the range function to go backwards as well as forwards, as in range(10,-1,-1). This will let us start at 10 and go down by 1's to 0.)
  5. Write a function similar to the ones above that moves a box along the diagonal of the canvas, from the upper left corner to as far down and to the right as you can go.
  6. Optional: Write a function similar to the previous one that moves a box along the other diagonal, from the upper right to as far down and left as you can go.
  7. Optional: You may modify any of these functions so that they take a picture to use as a background as a parameter.

Saving images and Creating a video file

    In order to create a video file, we will save each of the images that were created by calling one of the movement functions. The following function takes an array of images, a path to a folder on your Google drive, and the name to be used for the images. It then saves each image from the array into the specified folder, numbering them as it saves them.
        def writeArrayToJPGS(myArray, path, picName):
          for i in range(len(myArray)):
              myArray[i].save(path+"/"+picName+str(i)+".jpg","JPEG")
        
  1. Copy this function. To test that it works, do the following:
    1. Create a folder, called Boxes on your Google drive.
    2. Then do something like the following:
              myBoxes = moveBox()
              boxPath = '/drive/MyDrive/Colab Notebooks/Boxes'
              writeArrayToJPGS(myBoxes, boxPath, 'boxPic')
              
      This will save the array of images that gets produced in the 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.
  2. Lastly, we can then read all of the jpg files and write them to an mp4 file. The following function will do this for us:
            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()
            
    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:
    convertPicsToMovie(boxPath, 'box.mp4')

Moving Two Boxes

  1. Write a function that simultaneously moves one box across the top of the canvas, and another box across the bottom. You should be able to copy and paste your function from exercise #1 and add one or two lines of code. (Just add another filled rectangle to the canvas inside the for loop.)
  2. Optional: Write a function that simultaneously moves one box along the top-left-to-bottom-right diagonal, and another box from the top-right-to-bottom-left diagonal. Again, you should be able to modify either exercise #5 or #6 to do this.
  3. This function represents a more mathematically complicated way to get the boxes moving. One box moves down the canvas in a circular motion, while the other just moves down the diagonal of the canvas. Copy the following function and run it to see how it works.
    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
    
    

TickerTape

  1. Write a function that moves a text across a horizontal line. This should be similar to moving a box, except drawing text on the image instead of rectangles. (There is a sample function to do this in the Colab notebook that was shared with the class.)
  2. Write a function that moves text along a straight line, from top to bottom of the canvas.

(OPTIONAL) Submit your results

  1. Submit the file you created in this mini-lab via Kit.


>