How to save a matix as an image?
Show older comments
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 completly 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? Thank you in advance..
4 Comments
Adam
on 4 Mar 2016
The help for imwrite states:
Note: imwrite converts indexed images to RGB before writing data to JPEG files, because the JPEG format does not support indexed images.
So I would suggest saving to some other format if you just want 0 to 255 raw data saved.
Devadath Prabhu
on 4 Mar 2016
Adam
on 4 Mar 2016
I'm not an expert on different image formats, I literally just took a quick look at the Matlab help for imwrite and saw that. You can easily experiment with different file formats though.
Devadath Prabhu
on 4 Mar 2016
Accepted Answer
More Answers (5)
Image Analyst
on 4 Mar 2016
If your image is uint8, I recommend PNG. It's lossless compression. About a third the size of BMP and TIFF images. More than JPEG but with perfect quality, unlike the crummy images you can get from jpeg if you compress too much. Don't use jpeg for image analysis. Create your filename with a .png extension and you don't need to use the third argument for imwrite.
imwrite(rgbImage, 'fubar.png');
You can find out what other formats are allowed with the imformats command:
>> imformats
EXT ISA INFO READ WRITE ALPHA DESCRIPTION
-----------------------------------------------------------------------------------------
bmp isbmp imbmpinfo readbmp writebmp 0 Windows Bitmap
cur iscur imcurinfo readcur 1 Windows Cursor resources
fts fits isfits imfitsinfo readfits 0 Flexible Image Transport System
gif isgif imgifinfo readgif writegif 0 Graphics Interchange Format
hdf ishdf imhdfinfo readhdf writehdf 0 Hierarchical Data Format
ico isico imicoinfo readico 1 Windows Icon resources
j2c j2k isjp2 imjp2info readjp2 writej2c 0 JPEG 2000 (raw codestream)
jp2 isjp2 imjp2info readjp2 writejp2 0 JPEG 2000 (Part 1)
jpf jpx isjp2 imjp2info readjp2 0 JPEG 2000 (Part 2)
jpg jpeg isjpg imjpginfo readjpg writejpg 0 Joint Photographic Experts Group
pbm ispbm impnminfo readpnm writepnm 0 Portable Bitmap
pcx ispcx impcxinfo readpcx writepcx 0 Windows Paintbrush
pgm ispgm impnminfo readpnm writepnm 0 Portable Graymap
png ispng impnginfo readpng writepng 1 Portable Network Graphics
pnm ispnm impnminfo readpnm writepnm 0 Portable Any Map
ppm isppm impnminfo readpnm writepnm 0 Portable Pixmap
ras isras imrasinfo readras writeras 1 Sun Raster
tif tiff istif imtifinfo readtif writetif 0 Tagged Image File Format
xwd isxwd imxwdinfo readxwd writexwd 0 X Window Dump
7 Comments
Devadath Prabhu
on 5 Mar 2016
Image Analyst
on 5 Mar 2016
If you have a double image, use save() to save it as a mat file. Most of the standard image formats are for integer valued images.
Devadath Prabhu
on 6 Mar 2016
Walter Roberson
on 6 Mar 2016
If you use imwrite() to write uint8 or uint16 images, you will get back the same result when you read them unless you used an image format that uses lossy compression. JPG image format uses lossy compression and so should be avoided for this purpose. PNG and TIFF do not use lossy compression and so should be able to give you back exactly what you wrote.
If you use uint32 or uint64 then you might need to use special parameters or special ways to write the image, as not many image formats support those.
Devadath Prabhu
on 7 Mar 2016
Walter Roberson
on 7 Mar 2016
If you really want to write floating point numbers in an image format, then I suggest using the Tiff class, or DICOM format.
If your purpose is steganography then you are going about it the wrong way.
Image Analyst
on 21 Sep 2021
How? For tiff, this doesn't work:
grayImage = imread('cameraman.tif');
grayImage = double(grayImage) + rand(size(grayImage));
imwrite(grayImage, '_deleteme.tif');
recalledImage = imread('_deleteme.tif'); % It's uint8, not double
and for dicom, the documentation says this for the input image.
Data Types: int8 | int16 | uint8 | uint16
Guillaume
on 4 Mar 2016
Matlab consider the type of the matrix to establish what intensity range corresponds to fully dark-fully white.
If the matrix is of type double, then matlab uses the range 0-1 to represent intensities. Any value above 1 is considered the same as 1 and is maximum brightness. Hence your intensities 1 to 255 are all considered the same = white.
However, if the matrix is of type uint8, then matlab uses the range 0-255, just as you have. So convert your matrix to uint8:
imwrite(uint8(finalMat) 'myImage.jpeg');
3 Comments
Devadath Prabhu
on 4 Mar 2016
Edited: Devadath Prabhu
on 4 Mar 2016
Guillaume
on 4 Mar 2016
It is different in what way?
I assume that the values in finalMat are integers. If not, then there's no way you can save it as a jpg file without losing the decimals.
I also assume that your matrix is an 3D matrix (of size m x n x 3). If it's only a 2D matrix, you'll have to convert it to rgb before writing to jpg:
imwrite(repmat(uint8(finalMat), [1 1 3]), 'myImage.jpeg')
And to get your original image, just keep one of the page.
readIm = imread('myImage.jpeg');
readIm = readIm(:, :, 1);
Devadath Prabhu
on 4 Mar 2016
Edited: Devadath Prabhu
on 4 Mar 2016
Image Analyst
on 8 Jan 2022
Save it as a .mat file instead of an image format file
save('my floating point image.mat', 'myImage'); % Save myImage into a .mat file.
To recall it later:
s = load('my floating point image.mat'); % Load data in .mat file into a structure.
myImage = s.myImage; % Extract the floating point image from the structure.
1 Comment
Federico Fioretti
on 8 Jan 2022
I try to explain better what my problem is. I have a matrix of noninteger values and i have to save this matrix as an image because I have to use it later in an other software.
I have written a code that loads a file.mat in matlab, modifies it, and then i have to export this file (that is the matrix of non integers values) as an image format file. Can you help me?
Milind patil
on 10 Feb 2019
Brother, Simply use .png extension instead of .jpg.
imwrite(finalMat,'myImage.png');
This will give u exact values for sure.
11 Comments
Image Analyst
on 10 Feb 2019
It will NOT. Just try this:
m = 255 * rand(512); % Floating point in range 0-255.
imwrite(m, 'm.png'); % Save PNG file
mRecalled = imread('m.png'); % uint8 integers
isequal(m, mRecalled) % Returns false
delete('m.png') % Delete temporary test file.
and you will see.
Note from Devadath's comment that the numbers are floating point. If they were integers then what you say is true, but not in the floating point case.
DEEPAK DAIYA
on 14 Mar 2019
use
imwrite(mat2gray(finalMat),'myImage.jpeg','JPEG');
Image Analyst
on 14 Mar 2019
DEEPAK:
That also does not work:
finalMat = 255 * rand(512); % Floating point in range 0-255.
imwrite(mat2gray(finalMat),'myImage.jpeg','JPEG');
mRecalled = imread('myImage.jpeg'); % uint8 integers
whos mRecalled
isequal(m, mRecalled) % Returns false
delete('myImage.jpeg') % Delete temporary test file.
See, the recalled image is still uint8, not double, thus the values will change if there are any fractional values and it's not all integers.
Following the intention to save a floating point matrix as an image, I have tried first to normalize a TIF image (orinignally unit 8 as when is loaded with imread() funciton ) to have its values between 0 and 1.
However, when I try to write back the normalized matrix (a floating point matrix) to a TIF file image, it is saved agin as a unit 8 image (as the original one).
How could it be possible to save the foating potin matrix to a new TIF file image keeping the values between 0 and 1 obtained from the normalizartion of the original image and not get it saved back to unit 8?
% read image
im=imread('imge.tiff');
% convert to double
im = double(im);
% normalize between 0 and 1
im1 = (im-min(im(:)))/(max(im(:))-min(im(:)));
% save the normalized ijmage as TIF
imwrite(im1,'image_normalized_0_1.tiff');
% However when I relaod it is still the original unit 8 image not the normalized one:
im2 = imread('image_normalized_0_1.tiff');
Image Analyst
on 27 Nov 2020
To keep it as floating point, save it as a .mat file
% Save floating point image:
save('image_normalized_0_1.mat', 'im1');
% Recall floating point image:
s = load('image_normalized_0_1.mat');
im1 = s.image_normalized_0_1;
Yogesh Bhattarai
on 3 May 2021
last code results- Reference to non-existent field 'image_normalized_0_1'. ??
@Image Analyst, If im1 is the matrix ( with floating point values) , can you please explain how to save it as an image and then read it with the exact same values.
'.mat' doesn't give us an image right?
Image Analyst
on 21 Sep 2021
Edited: Image Analyst
on 21 Sep 2021
.mat does give the correct values, and it's an array, which means it's an image.
grayImage = imread('cameraman.tif');
grayImage = double(grayImage) + rand(size(grayImage));
save('_deleteme.mat', 'grayImage');
% Now read it back in to see if we get the same values.
s = load('_deleteme.mat')
recalledImage = s.grayImage % A double, as required.
Linh Nguyen
on 11 Oct 2021
I have a same problem, I want to get a .png file from complex double matrix.
Linh Nguyen
on 11 Oct 2021
Edited: Walter Roberson
on 8 Jan 2022
I want a .png file.
I have a double matrix.
img = imread('cameraman.tif'); img = double(img);
if I use:
imwrite(A, 'file_name.png');
it is different from imshow(A, []);
img = imread('cameraman.tif');
A = rescale(img);
imwrite(A, 'file_name.png');
imshow(img, []); title('original')
imshow(A); title('rescaled')
Linh Nguyen
on 11 Oct 2021
0 votes
@Milind patil give me your email - address, I want to ask about this topic. Do you find any way to solve it?
8 Comments
Federico Fioretti
on 8 Jan 2022
@Linh Nguyen Hi, I have your same problem. Have you found any way to solve it?
Image Analyst
on 8 Jan 2022
Edited: Image Analyst
on 8 Jan 2022
Save it as a .mat file instead of an image format file
save('my floating point image.mat', 'myImage'); % Save myImage into a .mat file.
To recall it later:
s = load('my floating point image.mat'); % Load data in .mat file into a structure.
myImage = s.myImage; % Extract the floating point image from the structure.
Federico Fioretti
on 9 Jan 2022
Thanks for the answer. I explain better my problem. I have a matrix with non-integers elements. I need to save this matrix in an image format (jpg or png) without losing the values, beacause I have to use this image later in an other photogrammetry sofrtware. So the .mat file is useless. Can you help me?
Federico Fioretti
on 9 Jan 2022
The matrix is a double matrix of non-integers values.
Image Analyst
on 9 Jan 2022
Edited: Image Analyst
on 9 Jan 2022
Tell me ALL the file formats your photogrammetry program can import.
Federico Fioretti
on 9 Jan 2022
Edited: Federico Fioretti
on 9 Jan 2022
.jpg .png .bmp .tiff for sure. The others I have to see in the PC i have in the office so now i can't.
also .dng and .raw files
Walter Roberson
on 9 Jan 2022
There is a File Exchange contribution that can write floating-point TIFF files.
Caution: it is not common for programs to support floating-point TIFF files. If I recall correctly, ImageJ does support them, but Windows Media does not; I am not sure about Adobe programs.
Image Analyst
on 9 Jan 2022
To save a floating point image as a TIFF file, this should do it.
% Create floating point image.
rgbImage = rand (10, 20, 3);
% Image must be single precision.
rgbImage = single(rgbImage);
% Display it.
imshow(rgbImage, 'InitialMagnification', 1000)
axis('on', 'image');
% Create tiff object.
fileName = '_floatingPointImage.tif';
tiffObject = Tiff(fileName, 'w')
% Set tags.
tagstruct.ImageLength = size(rgbImage,1);
tagstruct.ImageWidth = size(rgbImage,2);
tagstruct.Compression = Tiff.Compression.None;
tagstruct.SampleFormat = Tiff.SampleFormat.IEEEFP;
tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
tagstruct.BitsPerSample = 32;
tagstruct.SamplesPerPixel = size(rgbImage,3);
tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky;
tiffObject.setTag(tagstruct);
% Write the array to disk.
tiffObject.write(rgbImage);
tiffObject.close;
% Recall image.
m2 = imread(fileName)
% Check that it's the same as what we wrote out.
maxDiff = max(max(m2-rgbImage))
Categories
Find more on Image Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
