imwrite and imread are not giving the same matrix

4 次查看(过去 30 天)
Hello,
I want to show a matrix in an image (and save it for later use) and then retrieve the matrix from that image using imread. I followed the approach presented in https://www.mathworks.com/matlabcentral/answers/242747-how-can-i-convert-a-matrix-with-decimal-values-into-a-image-and-then-retrieve-the-same-matrix-back-f
However, while saving the image with the command imwrite, and then later read it with imread, I see two different matrices. Here is what I have done:
clear all, close all, clc
% A=rand(10); %random matrix(10x10) with values between 0 to 1.
% B=A*150;
B = [3 1; 2 5];
sz = size(B);
R = typecast(uint64(B(:) * 2^56),'uint8');
R1 = reshape(R, [8 sz]);
R2 = permute(flipud(R1), [2 3 1 4]);
R3 = reshape(R2, [sz(1), sz(2)*8, 1]);
imshow(R3);
imwrite(R3, 'TestFile.jpg')
close all
A = imread('TestFile.jpg');
sz = size(A);
U3 = reshape(A, [sz(1), sz(2)/8, 8, 1]);
U2 = flipdim(permute(U3, [3 1 2 4]),1);
UB = reshape(double(typecast(U2(:), 'uint64')) / 2^56, [sz(1), sz(2)/8, 1]);
Now my question is how to get the correct matrix from imread.
Thank you.
Khalid

采纳的回答

Walter Roberson
Walter Roberson 2020-11-18
This is normal and expected for image formats that use lossy compression, such as the way most people use jpeg.
You can:
  • tell imwrite to use jpeg lossless mode; or
  • use an image file format such as png that is lossless; or
  • arrange the data ahead of time to be flawed in exactly the same way that jpeg throws away data so that what gets written out matches what gets read in; or
  • adjust your expectations so that you no longer expect them to match.
I recommend that you adjust your expectations, and because of that, you stop using jpg for scientific work (jpeg2000 is a different matter and worth considering.)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Convert Image Type 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by