In this tutorial, we are going to learn how to display a matrix as an image in Python. This can be particularly useful in fields of Image Processing, Computer Vision, and Machine Learning, where images are often stored as 2-dimensional matrices. For this, we will be utilizing the Python libraries, NumPy and Matplotlib.
Step 1: Importing the Libraries
The first step in this process is to import the necessary libraries. We will need NumPy for matrix manipulation and Matplotlib for displaying the image. If you haven’t installed these already, you can do so by using pip:
1 |
pip install numpy matplotlib |
Once installed, we can import them into our script:
1 2 |
import numpy as np import matplotlib.pyplot as plt |
Step 2: Creating a Matrix
Next, we will need to create a matrix that we want to display as an image. In this example, let’s create a simple 5×5 matrix with values ranging between 0 and 255. NumPy makes this easy with its array function:
1 2 3 4 5 |
matrix = np.array([[56, 78, 101, 68, 87], [43, 91, 66, 191, 154], [50, 78, 255, 66, 190], [60, 90, 66, 192, 180], [56, 72, 98, 68, 120]]) |
Step 3: Displaying the Matrix as an Image
Now, we can display the matrix as an image using the imshow() function from the Matplotlib library. We’ll also use the show() function to display the plot:
1 2 |
plt.imshow(matrix, cmap='gray') plt.show() |
This code will display the matrix as a grayscale image. The cmap parameter is used to specify the color map. If you want to display the image in a different color map, you can change the cmap parameter to other available options such as ‘hot’, ‘cool’, ‘viridis’, etc.
The Full Code
By using the pieces of code from each step, you can assemble the full script:
1 2 3 4 5 6 7 8 9 10 11 |
import numpy as np import matplotlib.pyplot as plt matrix = np.array([[56, 78, 101, 68, 87], [43, 91, 66, 191, 154], [50, 78, 255, 66, 190], [60, 90, 66, 192, 180], [56, 72, 98, 68, 120]]) plt.imshow(matrix, cmap='gray') plt.show() |
Conclusion
In this tutorial, we’ve learned how to display a matrix as an image using Python’s Numpy and Matplotlib libraries. This can be an effective tool in displaying images in Python, especially in the contexts of image processing and machine learning.