imwrite, what it does with fractions and negative values
Show older comments
Hello,
This is an odd question, but how does imwrite handle fractions or negative inputs?
I am interested in reproducing this effect.
For example If I randomly generate some data and save it as an image and then read the saved image, I will see that matlab (somehow) assigned a uint8 value for each pixel. What modiciations do I need to perform to 'a' in order to get it to be equal to 'b' ?
Thank you for taking time to read this.
-James
clc
a = rand(2,10)-.5;
imwrite(a,'cake.jpg');
b=imread('cake.jpg');
a
b
Accepted Answer
More Answers (2)
You can change to using random integer function instead of rand function.
Also change the image format to png instead of jpg.
a = randi([0,255],2,10,'uint8');
imwrite(a,'cake.png');
b=imread('cake.png');
isequal(a,b)
1 Comment
James Latshaw
on 13 Jul 2021
Walter Roberson
on 13 Jul 2021
%approximately
function imwrite(data, filename)
if isfloat(data)
data = uint8(data * 255);
end
and so on
end
This is a simplification, as the 255 depends upon the bit depth options.
Notice that the range of the floating point data is not tested first. imwrite() does not check to see whether the data happens to be in the range 0.0 to 255.0 and if so then simply uint8() it: imwrite() multiplies all floating point data by 255. If the floating point data happened to have values greater than 1.0 then the result of the multiplication will be greater than 255.0, and no matter what range that turns out to be, it is then processed by uint8() [unless 16 bit output was requested.]
uint8() has its usual properties:
- any negative value "underflows" to 0.
- any value greater than 255 "saturates" to 255.
- any non-integer value is rounded to the nearest integer before being changed to integer data type.
1 Comment
James Latshaw
on 13 Jul 2021
Categories
Find more on Basic Display 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!
