Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert Matplotlib figure to PIL Image object?
Converting a Matplotlib figure to a PIL Image object allows you to manipulate the plot using PIL's image processing capabilities. This is useful when you need to apply filters, transformations, or integrate the plot into image processing workflows.
Step-by-Step Process
To convert a Matplotlib figure to PIL Image object, follow these steps −
- Set the figure size and adjust the padding between and around the subplots
- Create a new figure or activate an existing figure
- Plot your data using plot() method
- Initialize an in-memory buffer using
io.BytesIO() - Save the figure to the buffer in PNG format
- Use PIL Image to open the buffered image data
- Display or process the PIL Image object
- Close the in-memory buffer to free resources
Example
Here's a complete example that converts a simple line plot to a PIL Image ?
import io
from PIL import Image
import matplotlib.pyplot as plt
# Set figure parameters
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create and plot data
plt.figure()
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title("Sample Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Create in-memory buffer
img_buf = io.BytesIO()
# Save figure to buffer
plt.savefig(img_buf, format='png')
# Convert to PIL Image
img_buf.seek(0) # Reset buffer position
pil_image = Image.open(img_buf)
# Display image information
print(f"Image size: {pil_image.size}")
print(f"Image mode: {pil_image.mode}")
# Close buffer
img_buf.close()
plt.close() # Close matplotlib figure
Image size: (750, 350) Image mode: RGBA
Working with the PIL Image Object
Once you have the PIL Image object, you can perform various operations ?
import io
from PIL import Image, ImageFilter
import matplotlib.pyplot as plt
# Create matplotlib figure
plt.figure(figsize=(6, 4))
plt.plot([1, 2, 3, 4], [2, 1, 4, 3], 'ro-')
plt.title("Data Points")
# Convert to PIL Image
img_buf = io.BytesIO()
plt.savefig(img_buf, format='png', dpi=100)
img_buf.seek(0)
pil_image = Image.open(img_buf)
# Apply PIL operations
blurred_image = pil_image.filter(ImageFilter.BLUR)
resized_image = pil_image.resize((300, 200))
print(f"Original size: {pil_image.size}")
print(f"Resized size: {resized_image.size}")
# Clean up
img_buf.close()
plt.close()
Original size: (600, 400) Resized size: (300, 200)
Key Points
- Use
io.BytesIO()to create an in-memory buffer for the image data - Always call
img_buf.seek(0)before opening with PIL to reset the buffer position - Remember to close both the buffer and matplotlib figure to prevent memory leaks
- The resulting PIL Image will be in RGBA mode by default
- You can specify different formats like 'jpeg', 'pdf', or 'svg' in
savefig()
Conclusion
Converting Matplotlib figures to PIL Images enables powerful image processing workflows. Use io.BytesIO() as an in-memory bridge between Matplotlib and PIL, and always remember to properly close resources to avoid memory issues.
Advertisements
