How to prevent the saved images become uint8
조회 수: 12 (최근 30일)
이전 댓글 표시
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
Dyuman Joshi
2023년 9월 15일
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."
답변 (1개)
Walter Roberson
2023년 9월 15일
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
DGM
2023년 9월 17일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Convert Image Type에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!