Showing posts with label GIF. Show all posts
Showing posts with label GIF. Show all posts

Thursday, February 27, 2025

Can you create animation with Python? Part 1

It is possible to create simple animation with Python easily. This post shows how easy to create simple animation such as a GIF.

As the first step we create a wheel with a single spoke. We will then extend it to create a wheel with 5 spokes. 

The code for creating a circle with one spoke is as shown:

--------------------------------

from PIL import Image, ImageDraw

import numpy as np


def create_one_spoke_image(filename="one_spoke.png"):

    img_size = 500

    center = (img_size // 2, img_size // 2)

    radius = img_size // 4


    img = Image.new("RGB", (img_size, img_size), "white")

    draw = ImageDraw.Draw(img)


    # Draw the circle

    draw.ellipse((center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius), fill="black")


    # Draw ONE spoke (at 0 degrees for simplicity)

    x1 = center[0]

    y1 = center[1]

    x2 = center[0] + radius  # Spoke extends to the right

    y2 = center[1]

    draw.line((x1, y1, x2, y2), fill="red", width=3)


    img.save(filename)

    print(f"Saved: {filename}")

    img.show()


if __name__ == "__main__":

    create_one_spoke_image()

------------------------------------------------------

Here is the complete explanation of the code:


from PIL import Image, ImageDraw

import numpy as np

from PIL import Image, ImageDraw:

This line imports the Image and ImageDraw classes from the Python Imaging Library (PIL), also known as Pillow.

Image is used to create and manipulate image objects.

ImageDraw is used to draw shapes and lines on those image objects.

import numpy as np:

While numpy is imported, in this specific code provided, it is not actually utilized. If future modifications were to be made to the code, and array manipulation was needed, numpy would then be used.

2. Creating a Blank Image:

img_size = 500

img = Image.new("RGB", (img_size, img_size), "white")

img_size = 500:

This sets the size of the image to 500 pixels by 500 pixels.

img = Image.new("RGB", (img_size, img_size), "white"):

This creates a new image object.

"RGB" specifies that the image will be in RGB color mode (red, green, blue).

(img_size, img_size) sets the dimensions of the image.

"white" sets the initial background color of the image to white.

3. Creating a Draw Object:

draw = ImageDraw.Draw(img)

draw = ImageDraw.Draw(img):

This creates a Draw object associated with the img image.

The Draw object provides methods for drawing shapes, lines, and text onto the image.

4. Drawing a Circle:

center = (img_size // 2, img_size // 2)

radius = img_size // 4

draw.ellipse((center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius), fill="black")

center = (img_size // 2, img_size // 2):

This calculates the center coordinates of the image.

radius = img_size // 4:

This calculates the radius of the circle, which is one-quarter of the image size.

draw.ellipse(...):

This draws an ellipse (which will be a circle in this case, due to the equal width and height).

The coordinates (center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius) define the bounding box of the ellipse.

fill="black" sets the fill color of the circle to black.

5. Drawing a Spoke:

x1 = center[0]

y1 = center[1]

x2 = center[0] + radius  # Spoke extends to the right

y2 = center[1]

draw.line((x1, y1, x2, y2), fill="red", width=3)

x1 = center[0], y1 = center[1]:

These set the starting coordinates of the line (the spoke) to the center of the image.

x2 = center[0] + radius, y2 = center[1]:

These set the ending coordinates of the line. The spoke extends horizontally to the right, to the edge of the circle.

draw.line(...):

This draws a line between the starting and ending coordinates.

fill="red" sets the color of the line to red.

width=3 sets the thickness of the line to 3 pixels.

6. Saving the Image:

img.save(filename)

print(f"Saved: {filename}")

img.show()

img.save(filename):

This saves the created image to a file with the specified filename.

print(f"Saved: {filename}"):

This prints a confirmation message to the console.

img.show(): This line displays the image on a related printer as shown.

--------------------------------------------------------

When you run this code you will see the following:

C:\Users\hoden\AppData\Local\Programs\Python\Python312\python.exe C:\Users\hoden\PycharmProjects\exploreImage\Images\CircleOneSpoke.py 
Saved: one_spoke.png
Process finished with exit code 0

The following image is displayed:








Monday, December 23, 2024

Do you want to slow down a fast GIF?

GIFs are very engaging and dynamic images and they can run at a speed set at the time of creation. Well, some GIFs may look way better when run at a slow speed. 

You can use Python code to slow down a GIF that is too fast for your liking. In the previous post, you learnt how to make a GIF from scratch using Python. In this post, you will use Python code to slow down a GIF. The post shows an example.

Here is a GIF that is somewhat fast. It is copied from a website. 

Now here is the Python code that you can use to slow it down. The code shown is copied from my PyCharm user interface. If you copy and paste make sure the indentation requirements are satisfied.

from PIL import Image, ImageSequence
# Open the original GIF gif_path = 'lawn-time-lapse.gif'
gif = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images\lawn-time-lapse.gif')
# Create a list to hold the frames
frames = []
# Loop through each frame in the original GIF
for frame in ImageSequence.Iterator(gif):
# Append each frame to the list
frames.append(frame.copy())
# Save the frames as a new GIF with a slower speed
frames[0].save('slowed_down_1_gif.gif', save_all=True, append_images=frames[1:],
duration=200, loop=0)
print('Slowed down GIF saved as slowed_down_1_gif.gif')

The fast GIF is in the project folder in the path shown. The ImageSequence is the key. You get a sequence of images in the frame that you append to a list. Save the frames as a new GIF with a slower speed. Duration in PIL is absolute in milliseconds.

The code before the print saves the first frame(frames[0]) and it saves all the frames slowing down to a duration of 200 seconds and appends the rest of the frames starting from frame[1], the second frame in the sequence.

Here is the result of slowing down the original GIF.


Since we have a handle to the sequence, we can find the original frames and the original duration as well.


Sunday, December 22, 2024

You have seen a GIF, have you created one?

  You have seen a GIF image and enjoyed it. But have you created one.? There are software programs to create GIFs and perhaps many online sites help creating GIFs.  Here is one for example, https://www.canva.com/create/gif-maker/. Animation akin to GIFS can also be created using javascript although there may not be resulting image with a .gif extension.

GIFs are like very small duration video clips but they are really a composite of many small images flipped rapidly, in-situ to create the illusion of motion. They are made to impress you by their motion.

Why GIFS?

Imagine bringing life to a still photo of a sunset by animating the clouds. An image may be worth a thousand words, but a GIF is worth a thousand images. It adds dynamic movement to static images, unleashing your creativity. If you're active on social media, GIFs are an invaluable tool for self-expression, offering endless possibilities. They bring humor, emotion, and laughter to any page, transforming a collection of static images into a vibrant and engaging experience. With GIFs, you can elevate your storytelling to new heights!"

Here is a simple GIF image copied from a web site  (display gif on web browser - Search):


Ins and outs of using Python to create GIFs:

GIF images have the .gif extension which stands for Graphics Interchange Format. 

In this post, I show you how to create from scratch a GIF using Python. Python uses a image library such as PIL to get the images into the program such as PyCharm. Once they are in the program, you need to use another library to do the flipping action. This library is called imageio, image input/output program. For GIFs this program takes in the images (a number of them) and then it customizes the duration each image is shown; whether the gif repeats itself and how many times it does, etc. Note: if you are new to PyCharm, read up my other Python/Image related posts in this blog, http://hodentekhelp.blogpost.com.

The program presented here also goes through the indexing of the images (as there are many images) which necessitate calling yet another useful library called NumPy. The imageio program cannot accept a image list, but a Numpy list and hence the use of the NumPy library.

In order to create a gif file in a python program, you need the following:

1. A set of images. 

2. Importing libraries PIL, ImageIO and Numpy.

Here is are some five image files I am using in the program:






These are not the best, but enough for the purpose.

Here is the python program that creates a GIF image taking in the images shown here:

----------------------------

BirdsGIF.py

-----------------

# Import libraries used to create a GIF image

import imageio

import numpy as np

from PIL import Image

from PIL.ImageFile import ImageFile

# Load images

image1: ImageFile = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird1.jpg')

image2 = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird2.jpg')

image3 = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird3.jpg')

image4 = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird4.jpg')

image5 = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird5.jpg')

# Resize images (optional)

image1 = image1.resize((200, 200))

image2 = image2.resize((200, 200))

image3 = image3.resize((200,200))

image4 = image4.resize((200,200))

image5 = image5.resize((200,200))

# Create list of images

images = [image1, image2, image3, image4, image5]

# Convert PIL image  list to NumPy arrays

images = [np.array(img) for img in images]

# Create the GIF using the image list

imageio.mimsave('my_animation.gif', images, duration=2000.0, loop=5)

----------------------

The above program creates a image file with .gif extension and images show for 2000 milliseconds and the GIF image runs five times in succession. If you have time elapsed stills of any event you can easily turn it into an amazingly dynamic image.

That is all there is to creating a GIF. If your images are made with care and are of good quality you can indeed create a good GIF.

The GIf file created, my_animation.gif can be seen in Photo app on your windows computer device, however you can just drag and drop the image on a browser should also work.


Mahalo for staying with me. 

p.s: For these holidays, you can create your greeting card with a GIF. Try it!