MATLAB Answers

How to save actual values in a matrix as an image in matlab?

133 views (last 30 days)
marjan ss
marjan ss on 30 Oct 2017
Commented: Image Analyst on 14 Mar 2021
I have a matrix in matlab with 10 different values. All values in my array are integer from 1 to 10. I need to save this matrix as an image (image.jpg). However I want to have the same values ( integers from 1 to 10) in my image when I read the image into the matlab. When I use imwrite or save or saveas I create an image but when I read it into matlab, values are from 0-255 no form 1-10.

Answers (1)

Image Analyst
Image Analyst on 30 Oct 2017
imwrite should work. It's not enough that they are integers, they must be uint8 integers, not double values that happen to have integer values. Try this:
imwrite(uint8(myData), 'my image.png');
Image Analyst
Image Analyst on 14 Mar 2021
I always use uint8() and uint16() because I never know if or how the im2uint8() and im2uint16() functions shift intensities or scale the image to fit into the 8 bit or 16 bit range. Like if you have a double with min value of 1000 and max value of 45000, does it leave it as a range [1000-45000] or does it scale it to 0-65535 for uint16? I know that uint8 and uint16 never scale or shift intensity ranges.If they are known to be out of range then I call rescale() or mat2gray() before calling uint8() or uint16(). I prefer to scale it myself so I know what's going on.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by