How to prevent the saved images become uint8
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Dear Admin,
This is my code:
filename = 'D:\files.txt';
grayImage = transpose(importdata(filename));
a = readmatrix(filename);
imwrite(a', 'files.png');
I want to read a 2D array (512x512 with double type) from a matrix file named ‘files.txt’. However, when I try to save this matrix as an image, the data type of the image becomes uint8.
My problem is how to preserve the original data type (double) from ‘files.txt’ when saving it as an image?
Regards,
2 comentarios
Dyuman Joshi
el 15 de Sept. de 2023
That's not possible.
The default behaviour when using imwrite is to convert the bit depth to uint8. Exceptions include some image types that can be saved as uint16.
As your file is a 2D array of double type, I assume it is a grayscale image.
From the documentation of imwrite - "If A is a grayscale or RGB color image of data type double or single, then imwrite assumes that the dynamic range is [0, 1] and automatically scales the data by 255 before writing it to the file as 8-bit values."
Respuestas (1)
Walter Roberson
el 15 de Sept. de 2023
PNG has no support for floating point pixels.
TIFF has support for floating point, but the imwrite() interface to TIFF does not support that.
See https://www.mathworks.com/matlabcentral/answers/307519-image-file-saved-using-tiff-library-tif-appear-white-in-explorer-and-paintbrush#answer_239772 for sample direct MATLAB code
See https://www.mathworks.com/matlabcentral/fileexchange/30519-export-image-to-tif-or-tiff-file-of-selected-data-type for a File Exchange contribution that knows how to deal with the various different TIFF output types. (Except possibly COMPLEX)
5 comentarios
DGM
el 17 de Sept. de 2023
I think it's worth emphasizing that the solution depends less on MATLAB and more on whatever other application you expect to read the file. Most image viewers and editors (at least that I've tried) won't open a floating-point TIFF (or at least not correctly).
Similarly, you might be able to typecast the data and pack it into a PNG for transport, but most other applications will have no way of reversing the process, and any modifications performed on the packed image will destroy it.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1484577/image.png)
If the target application supports no formats that are capable of floating-point, then that's that. If there is no target application, and all you are concerned with is using it in MATLAB, then why not use a MAT file or something? A MAT file will be reasonably compact and convenient to use -- at least within MATLAB.
Ver también
Categorías
Más información sobre Convert Image Type en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!