Back to Python
2026-01-095 min read

Shake an Image (Python Programming)

Learn Shake an Image (Python Programming) step by step with clear examples and exercises.

Why This Matters

In this lesson, we will learn how to create a Python program that shakes an image. This skill is essential for developers who work on multimedia applications or websites, as it allows them to add dynamic and engaging effects to images. It can also be useful in debugging and testing, as shaking an image can help identify issues with the underlying code or data.

Prerequisites

To follow this lesson, you should have a basic understanding of Python programming and be familiar with the following concepts:

  • Variables and data types
  • Functions and modules
  • File I/O (Input/Output)
  • Basic image manipulation using the PIL (Python Imaging Library)

Core Concept

The Python Imaging Library (PIL) is a powerful, open-source library for handling images in Python. It provides various functions and classes to read, modify, and write images in different formats such as JPEG, PNG, and GIF. In this lesson, we will use the ImageChops module of PIL to create an image shake effect.

The ImageChops module contains several methods for performing various operations on images, such as changing brightness, contrast, and color. One of these methods is shift, which moves every pixel in an image by a specified amount along the x-axis or y-axis. By applying this method repeatedly with random shifts, we can create the illusion of an image shaking.

Here's a step-by-step breakdown of creating a simple image shake effect:

  1. Import the necessary modules (Image, ImageChops, and random).
  2. Open the input image using the open() function from the Image module.
  3. Create an empty list to store the shaken images.
  4. Loop through a specified number of iterations. In each iteration:
  • Apply the shift() method from ImageChops to create a new image with a random shift along the x-axis or y-axis.
  • Append the shaken image to the list.
  1. Save the final shaken image using the save() function from the Image module.
from PIL import Image, ImageChops, ImageOps
import random

Open the input image

img = Image.open('input.jpg')

Create a list to store the shaken images

shaken_images = []

Specify the number of iterations for shaking

num_iterations = 100

Loop through each iteration

for _ in range(num_iterations):

Apply random shift along x-axis or y-axis

shaken_img = ImageChops.shift(img, (random.randint(-5, 5), random.randint(-5, 5)))

Append the shaken image to the list

shaken_images.append(shaken_img)

Save the final shaken image

shaken_images[-1].save('output.gif', save_all=True, append_images=shaken_images[:-1])


In this example, we open an input JPEG image (`input.jpg`) and create a GIF output (`output.gif`) containing 100 shaken versions of the original image. The `shift()` method is applied with random shifts along both axes to create a more dynamic shake effect.

Worked Example

Let's work through an example together. In this example, we will create a Python script that shakes an input image and saves the result as a GIF.

  1. First, make sure you have the PIL library installed. If not, install it using pip:
pip install pillow
  1. Create a new Python file (e.g., shake_image.py) and paste the following code into it:
from PIL import Image, ImageChops, ImageOps
import random
import sys

Check if an input image is provided as command-line argument

if len(sys.argv) != 2:

print("Usage: python shake_image.py ")

exit()

Open the input image

img = Image.open(sys.argv[1])

Create a list to store the shaken images

shaken_images = []

Specify the number of iterations for shaking

num_iterations = 100

Loop through each iteration

for _ in range(num_iterations):

Apply random shift along x-axis or y-axis

shaken_img = ImageChops.shift(img, (random.randint(-5, 5), random.randint(-5, 5)))

Append the shaken image to the list

shaken_images.append(shaken_img)

Save the final shaken image

shaken_images[-1].save('output.gif', save_all=True, append_images=shaken_images[:-1])


3. Save the file and run it from the command line by providing an input image as an argument:

python shake_image.py input.jpg


This script will create a GIF (`output.gif`) containing 100 shaken versions of the provided input image (`input.jpg`). You can adjust the number of iterations by changing the `num_iterations` variable in the code.

Common Mistakes

  • Forgetting to import the necessary modules (Image, ImageChops, and random)
  • Not providing an input image as a command-line argument when running the script
  • Using an unsupported image format for the input or output files
  • Not saving the final shaken image properly (e.g., using the wrong file name, extension, or directory)

Mistake 1: Forgetting to import modules

Incorrect code

from PIL import ImageChops

import random

Corrected code

from PIL import Image, ImageChops, ImageOps

import random


### Mistake 2: Not providing an input image as a command-line argument

Incorrect script

def main():

... (rest of the code)

if __name__ == "__main__":

main()

Incorrect usage

python shake_image.py

Correct usage

python shake_image.py input.jpg


### Mistake 3: Using an unsupported image format

Incorrect code (using BMP instead of JPEG)

img = Image.open('input.bmp')

Corrected code (using JPEG instead of BMP)

img = Image.open('input.jpg')


### Mistake 4: Not saving the final shaken image properly

Incorrect code (saving as a PNG instead of GIF)

shaken_images[-1].save('output.png', save_all=True, append_images=shaken_images[:-1])

Corrected code (saving as a GIF)

shaken_images[-1].save('output.gif', save_all=True, append_images=shaken_images[:-1])

Practice Questions

  1. Modify the script to shake an image horizontally only (i.e., shifts along the x-axis but not the y-axis).
  2. Create a function that takes two images as input and returns a shaken version of both images combined into a single GIF.
  3. Modify the script to allow users to specify the number of iterations via a command-line argument (instead of hardcoding it in the script).
  4. Experiment with different values for the random shifts to create more dramatic or subtle shake effects.

FAQ

Q: What if I want to shake an image vertically only?

A: To shake an image vertically only, you can modify the shift() method in the code to apply shifts along the y-axis instead of the x-axis.

Q: Why does my shaken image look blurry or pixelated?

A: Blurriness or pixelation may occur due to excessive shaking or low-quality input images. You can experiment with reducing the number of iterations or using higher-resolution input images to improve the quality of the shaken output.

Q: Can I use this technique for video shake effects?

A: Yes, you can adapt this technique to create shake effects for videos by using a library like OpenCV instead of PIL. However, keep in mind that working with videos requires more computational resources and may be more complex than working with images.

Shake an Image (Python Programming) | Python | XQA Learn