Ramya Soundar
Ramya Soundar

Reputation: 41

Save a matrix as an image

I have a matrix finalMat of data type double with values in the range of 0 to 255. It actually corresponds to some image. I am displaying it as below:

imshow(finalMat, []);

But when I try to save it using the below code, the image saved is completely white.

imwrite(finalMat,'myImage.jpeg','JPEG');

I want to save the image on disk without changing the values in the finalMat matrix. When I read the saved image i.e myImage.jpeg, I must get the same values as in finalMat. Can somebody please help in saving the image?

Upvotes: 4

Views: 6450

Answers (1)

Suever
Suever

Reputation: 65430

imwrite first checks the datatype prior to writing the file to determine how to treat the values in the input. If the input is a double, is assumes that the range is 0 to 1. If the input is a uint8, then it assumes [0, 255].

Your two options are to cast the data as uint8 or normalize it between 0 and 1 and keep it as a double.

Cast as a uint8

For your specific example, you already have data between 0 and 255 and presumably don't want that data scaled, so you'll likely want to go the uint8 cast route.

imwrite(uint8(finalMat), 'file.jpg');

Keep in mind that since you have a double image matrix, this will force all the numbers to be integer values so it may not be exactly equal when you load it back into MATLAB.

Normalize Image Data

More generally speaking, you'll typically want to go with the normalization approach using mat2gray to do the normalization for you which allows you to utilize the full 8-bit range.

imwrite(mat2gray(finalMat), 'file.jpg')

NOTE: You mention that you want the resulting image to be exactly equal to the matrix that you're passing into it. Unfortunately, your input data is a double which requires 64 bits per pixel. None of the imaging formats supported by MATLAB can actually store all 64 bits so you're going to end up with some differences regardless of how you do this. If you want to minimize this effect, look for an image format that supports 16 or 32-bit data (the JPEG you're currently creating is 8-bit). Also, I would recommend against using JPEG as this is potentially a lossy type of compression. If you want lossless compression, go with a TIFF or PNG.

Upvotes: 3

Related Questions