Home > Article > Backend Development > How to Directly Write Numpy Arrays to Image Files Without External Dependencies?
Direct Disk Write of Numpy Arrays as Images
For those requiring flexibility in image file formats without the constraints of external dependencies like PIL, the following approach allows for direct disk writes of Numpy arrays as images:
Saving an Array as an Image:
Sample Code:
import numpy as np from scipy.ndimage import imwrite # or import cv2 and use cv2.imwrite for OpenCV # Create a NumPy array representing the image image_array = np.zeros((512, 512, 3), dtype=np.uint8) # Save the array as a PNG image imwrite('my_image.png', image_array)
Additional Note:
If working with multi-channel arrays (e.g., representing RGB images), ensure that the dtype of the array matches the channel convention. For instance, for RGBA images, use np.uint32.
The above is the detailed content of How to Directly Write Numpy Arrays to Image Files Without External Dependencies?. For more information, please follow other related articles on the PHP Chinese website!