MATLAB Answers

0

write and read the same image but they are different

Asked by lol lolol on 10 Sep 2019
Latest activity Commented on by Guillaume
on 11 Sep 2019
Hi, I would like to save exact copy of image.
When I use
imwrite(image, 'image.png');
and after that:
image2=imread('image.png')
and try to compare this images they are different- but I dont see any differenceces(imabsdiff also)
psnr(image,image2)
ssim(image,image2)
PSNR = 18.600852547147856
SSIM = 0.091853247350195
both images are double class
What I can do to have the same pixel by pixel images?

  1 Comment

Comment posted as answer by lol lolol:
image is a double class, I don't know how imwrite and imread works, but when I try to make image2 a double class, it's still a different image.
I checked one pixel and values are different:
image =
0.298940255146088
image2 =
0.298039215686275
Any suggest how to fix it?

Sign in to comment.

1 Answer

Answer by Rik
on 11 Sep 2019

You should read the documentation of the functions you're using if you want to understand them. Matlab has excellent documentation, it is one of the things that is better than most alternatives.
If you want to have the exact same image, you need to make sure there is no lossy compression in the file format and that you don't have any float rounding. The png format is lossless, so no problem there. If you want to store and retrieve images, they will generally be stored as uint8, instead of double. You haven't attached any example files to reproduce your issue, so I can't be more specific than this.
Also, you shouldn't shadow the internal image function with a variable name. That can in some cases cause issues. Before assigning a variable, you can use the which function to find out if the name is in use by a function you may need.

  4 Comments

Show 1 older comment
"so imwrite is the reason"
Not at all: the PNG image format does not support floating point numbers, so what do you expect to happen? As a courtesy to the user, imwrite scales the floating point numbers to appropriate values and converts them to uint8 (which is supported by PNG).
The only image file format that I am aware of that supports floating point numbers is TIFF (which supports 32 bit single).
Why do you need to save it as an image rather than as actual data? If you want that level of accuracy then you should be saving just the data, not an image. Those type of differences are almost impossible to see with the eye though usually, which is the only purpose of an image over just the raw data.
There's only a few image formats that support storing pixel intensities as floating point values. tiff is one of them but imwrite doesn't support that.
Any double image written by imwrite will therefore be discretised. If using png, you have the option to discretise it to 8 bits (256 levels) or 16 bits (65536 levels) if you convert it to uint16 (with im2uint16).
Other common image formats such as BMP and jpeg are typically 8-bit only.

Sign in to comment.