i have a double array and i want to convert that to an image but when i am doing so all the pixel values is getting converted to 255
12 views (last 30 days)
Show older comments
i have a double array and i want to convert that to an image but when i am doing so all the pixel values is getting converted to 255
2 Comments
Answers (3)
Jan
on 21 Jan 2019
Edited: Jan
on 21 Jan 2019
Maybe all you have to do is to normalize the array:
% Normalize the range [0, a] to [0, 1]
img = X / max(X(:));
If the original array X contains non-negative values only, the range is set to [0, 1]. This can be displayed as image directly.
[EDITED] Alternatively:
% Normalize [a, b] to [0, 1]:
maxx = max(X(:));
minx = min(X(:));
img = (X - minx) / (maxx - minx);
0 Comments
Walter Roberson
on 21 Jan 2019
When you imwrite() data that is single() or double(), then the usable data range is 0.0 to 1.0 and all values below 0.0 will be internally converted to 0.0 and all values above 1.0 will be internally converted to 1.0. After that if you are writing to any image type (such as JPEG) that does not support floating point, then the values will be converted to uint8 and the uint8 will be written.
In short: your problem is that you have double values that are greater than 1.
If you need to definitely continue to write as double, then you will need to switch image file formats to TIFF and use the Tiff class to do the writing, such as is described at https://www.mathworks.com/matlabcentral/answers/7184-how-can-i-write-32-bit-floating-point-tifs-with-nans#comment_15023 .
Most of the time, though, people have used double() of a uint8 image for processing purposes, getting double that holds 0.0 to 255.0, and then they expect that if they imwrite() that out, that they will get the image they expect. That does not work because 255.0 somehow designates a pixel at 255 times maximum intensity, being different than uint8(255) which is plain maximum intensity. You would uint8() the double before imwrite() in this situation.
1 Comment
Image Analyst
on 21 Jan 2019
To leave the image in it's original range and class (double), to display it, use [] in imshow():
imshow(yourDoubleArray, []); % Note the []
If you want to save it, you'll have to scale it to 0-1 with mat2gray(), and then convert to uint8
image8 = uint8(255 * mat2gray(yourDoubleArray));
imwrite(image8, filename);
See Also
Categories
Find more on Convert Image Type 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!