Sai A Sai A
Updated date Mar 13, 2024
In this blog, we will learn how to convert a dictionary into an image using Python. This blog explores two methods - one using the Python Imaging Library (PIL) and the other using Matplotlib.

Method 1: Using PIL (Python Imaging Library)

The Python Imaging Library, commonly known as PIL or its fork Pillow, is a powerful library for image processing tasks. We can use PIL to convert a dictionary into an image. First, let's take a look at a simple dictionary representing pixel values:

# Dictionary representing pixel values
pixel_data = {
    (0, 0): (255, 255, 255),  # White pixel at (0, 0)
    (1, 0): (255, 0, 0),      # Red pixel at (1, 0)
    (2, 0): (0, 255, 0),      # Green pixel at (2, 0)
    # Add more pixel values as needed
}

Next, we will use PIL to create an image from this dictionary:

from PIL import Image

# Create a new image
image = Image.new("RGB", (3, 1))

# Assign pixel values from the dictionary
for (x, y), color in pixel_data.items():
    image.putpixel((x, y), color)

# Save the image
image.save("output_method1.png")

Output:

 The output of the above program will be an image file named "output_method1.png" representing the pixel values specified in the dictionary.

Method 2: Using Matplotlib

We use the popular library Matplotlib for creating visualizations in Python. While it is primarily used for plotting graphs and charts, it can also be used to generate images from data. Here's how we can achieve it:

import matplotlib.pyplot as plt

# Extract pixel values from the dictionary
pixels = [pixel_data.get((x, y), (0, 0, 0)) for x in range(3) for y in range(1)]

# Reshape pixel values into an image
image_data = [pixels[i:i + 3] for i in range(0, len(pixels), 3)]

# Display the image
plt.imshow(image_data)
plt.axis('off')  # Hide axes
plt.savefig("output_method2.png", bbox_inches='tight', pad_inches=0)
plt.show()

Output:

The output of this method will also be an image file named "output_method2.png" representing the pixel values specified in the dictionary.

Comments (0)

There are no comments. Be the first to comment!!!