To convert a NumPy array to an image, you can use the cv2.imwrite()
function from the OpenCV library. This function allows you to save the NumPy array as an image file on your disk. Here’s an example:
import numpy as np import cv2 # Create a NumPy array representing an image image_array = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]], dtype=np.uint8) # Save the NumPy array as an image file output_file = "image.jpg" cv2.imwrite(output_file, image_array) # Read the saved image file to verify read_image = cv2.imread(output_file) cv2.imshow("Converted Image", read_image) cv2.waitKey(0) cv2.destroyAllWindows()
In this example, we first create a NumPy array image_array
that represents an image. The array contains RGB values for each pixel, represented as 8-bit unsigned integers.
Then, we use the cv2.imwrite()
function to save the NumPy array as an image file. The first argument is the output file path, and the second argument is the NumPy array. The function will write the array data into the specified image file.
Finally, we use cv2.imread()
to read the saved image file back into a new NumPy array read_image
. We display this image using cv2.imshow()
to verify that the conversion was successful.
When you run the code, it will save the NumPy array as an image file named “image.jpg” in the current directory. It will also display the converted image in a window using OpenCV.