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 show numpy 2D array as grayscale image in Jupyter Notebook?
To show a NumPy 2D array as a grayscale image in Jupyter Notebook, you can use Matplotlib's imshow() function with the cmap='gray' parameter. This technique is commonly used for visualizing data matrices, image processing, and scientific computing.
Basic Example
Here's how to display a 2D array as a grayscale image ?
import matplotlib.pyplot as plt
import numpy as np
# Create a 2D array with random values
data = np.random.rand(5, 5)
print("Array values:")
print(data)
# Display as grayscale image
plt.imshow(data, cmap='gray')
plt.title('2D Array as Grayscale Image')
plt.colorbar() # Shows the value-to-color mapping
plt.show()
Array values: [[0.37454012 0.95071431 0.73199394 0.59865848 0.15601864] [0.15599452 0.05808361 0.86617615 0.60111501 0.70807258] [0.02058449 0.96990985 0.83244264 0.21233911 0.18182497] [0.18340451 0.30424224 0.52475643 0.43194502 0.29122914] [0.61185289 0.13949386 0.29214465 0.36636184 0.45606998]]
Working with Different Data Types
You can visualize various types of 2D data as grayscale images ?
import matplotlib.pyplot as plt
import numpy as np
# Create different types of 2D arrays
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
# 1. Integer array
int_data = np.array([[0, 50, 100], [150, 200, 255], [75, 125, 175]])
axes[0].imshow(int_data, cmap='gray')
axes[0].set_title('Integer Array')
axes[0].axis('off')
# 2. Sine wave pattern
x = np.linspace(0, 2*np.pi, 50)
y = np.linspace(0, 2*np.pi, 50)
X, Y = np.meshgrid(x, y)
sine_data = np.sin(X) * np.cos(Y)
axes[1].imshow(sine_data, cmap='gray')
axes[1].set_title('Sine Wave Pattern')
axes[1].axis('off')
# 3. Distance matrix
distance_data = np.sqrt(X**2 + Y**2)
axes[2].imshow(distance_data, cmap='gray')
axes[2].set_title('Distance Matrix')
axes[2].axis('off')
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example Values |
|---|---|---|
cmap |
Colormap for grayscale | 'gray', 'Greys', 'binary' |
vmin, vmax |
Value range for color mapping | vmin=0, vmax=1 |
interpolation |
Image smoothing | 'nearest', 'bilinear' |
Advanced Example with Custom Settings
import matplotlib.pyplot as plt
import numpy as np
# Create a more complex 2D array
size = 100
center = size // 2
y, x = np.ogrid[:size, :size]
mask = (x - center)**2 + (y - center)**2 <= (size//3)**2
data = np.zeros((size, size))
data[mask] = 1
# Add some noise
data += np.random.normal(0, 0.1, (size, size))
# Display with custom settings
plt.figure(figsize=(8, 6))
plt.imshow(data, cmap='gray', vmin=0, vmax=1, interpolation='bilinear')
plt.title('2D Array with Custom Grayscale Mapping', fontsize=14)
plt.colorbar(label='Intensity')
plt.xlabel('X pixels')
plt.ylabel('Y pixels')
plt.show()
print(f"Array shape: {data.shape}")
print(f"Value range: {data.min():.3f} to {data.max():.3f}")
Array shape: (100, 100) Value range: -0.312 to 1.298
Conclusion
Use plt.imshow(array, cmap='gray') to visualize 2D NumPy arrays as grayscale images. Add plt.colorbar() to show the value-to-intensity mapping, and adjust vmin/vmax parameters to control the contrast and brightness of your visualization.
Advertisements
