pythonimagematplotlibmatrixsave

How to Save a Matrix as a PNG Image and Reload it to Recover the Original Matrix


I would like to save a 96x96 matrix as an image. The values in the matrix range from -1 to 1. When I save the matrix using

plt.imsave(path, matrix, cmap='rainbow'),

it gets stored as a 96x96x4 RGBA image, and each channel's values are rescaled to the 0–255 range. This makes it difficult to retrieve the original values of the matrix. Is there a way to preserve the original matrix values when saving and reloading the image?

I attempted the following approach to retrieve the original matrix:

loaded_image = plt.imread(path)
restored_image = np.mean(loaded_image[:, :, :3], axis=2)
print(restored_image )

However, this method only reproduces a matrix with the same dimensions as the original matrix, but the values differ from those of the original matrix.


Solution

  • There is not a single good answer to your question, as it is not quite clear to me why you want to save your matrix as an image in the first place. Consider the following: Most images that are used in standard use cases (think of showing pictures online, creating plots of data, etc.) are 8-bit RGB(A) or grayscale images, meaning you have 3 or 4 channels for RGB (red, green, blue, and maybe opacity) or 1 channel for grayscale (intensity), each storing 256 integer values (0 to 255). Your data, on the other hand, is floating point data in a very different range (-1 to 1). So a standard, 8-bit image may not be the ideal medium to store your matrix.

    There are multiple options you could choose from, depending on the actual task that you are trying to solve: