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 save an array as a grayscale image with Matplotlib/Numpy?
To save an array as a grayscale image with Matplotlib/NumPy, we can use imshow() with the gray colormap and savefig() to save the image to disk.
Basic Example
Here's how to create and save a grayscale image from a NumPy array ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create random data with 5x5 dimension
arr = np.random.rand(5, 5)
# Display as grayscale image
plt.imshow(arr, cmap='gray')
plt.colorbar() # Add colorbar to show intensity scale
plt.title('Grayscale Image from Array')
# Save the image
plt.savefig('/images/grayscale_output.png', dpi=300, bbox_inches='tight')
plt.show()
Saving Without Axes and Borders
To save just the image data without matplotlib's axes and borders ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
data = np.random.rand(100, 100)
# Create figure without axes
fig, ax = plt.subplots()
ax.imshow(data, cmap='gray')
ax.axis('off') # Remove axes
# Save with tight bounding box
plt.savefig('/images/clean_grayscale.png', bbox_inches='tight',
pad_inches=0, dpi=150)
plt.show()
Using Different Grayscale Ranges
Control the intensity range with vmin and vmax parameters ?
import numpy as np
import matplotlib.pyplot as plt
# Create data with specific range
data = np.array([[0, 0.3, 0.6],
[0.2, 0.5, 0.8],
[0.4, 0.7, 1.0]])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# Default range (0-1)
ax1.imshow(data, cmap='gray')
ax1.set_title('Default Range')
ax1.axis('off')
# Custom range (0.2-0.8)
ax2.imshow(data, cmap='gray', vmin=0.2, vmax=0.8)
ax2.set_title('Custom Range (0.2-0.8)')
ax2.axis('off')
plt.tight_layout()
plt.savefig('/images/grayscale_ranges.png', dpi=200)
plt.show()
Key Parameters
| Parameter | Description | Common Values |
|---|---|---|
cmap |
Colormap for grayscale | 'gray', 'Greys' |
dpi |
Image resolution | 150, 300, 600 |
bbox_inches |
Bounding box control | 'tight', None |
pad_inches |
Padding around image | 0, 0.1, 0.2 |
Conclusion
Use plt.imshow() with cmap='gray' to display arrays as grayscale images. Use plt.savefig() with appropriate parameters to save high-quality images to disk.
Advertisements
