MATLAB Answers

Generate same array as what imwrite produces from a double array

2 views (last 30 days)
Omkar Karve
Omkar Karve on 8 Apr 2021
Commented: Omkar Karve on 11 Apr 2021
I have a double array "im" of size (224,224,3) with values between -0.1472 and 1.1472. I take this array and use imwrite(im, imfilename) to generate a jpg. If I read back this jpg image file using imread I get an array of same size (224,224,3) but the values are from 0 to 255.
My question is how can I generate the same values (from 0 to 255) as what I get by doing imread on the jpg file from my original array without using the intermediate process of imwrite and imread?

Accepted Answer

DGM
DGM on 9 Apr 2021
Edited: DGM on 9 Apr 2021
I can answer that question, but I don't know that you mean to be doing the thing you're trying to do.
Most IPT tools assume that image data of class 'double' has a black value of 0 and a white value of 1. These are the values that are of importance when the data is rescaled/truncated when converting between classes. When you do your imwrite/imread routine, what's happening is that imwrite() gets fed an image of class 'double'. In order to scale the data to 'uint8', it's going to discard anything outside of [0 1] and rescale the remaining to fit [0 255]. You've truncated the data.
If this truncation is desired, then you can do it like this:
mydoublepic = rand(100)*1.2944-0.1472;
myuint8pic = im2uint8(mydoublepic); % if you have IPT
%myuint8pic = uint8(mydoublepic*255); % if you don't have IPT
If truncation is undesired, then the question becomes whether you want the output data to be 'uint8' at all, or whether you simply want it rescaled. If you want it to be 'uint8', then you'd have to scale it somehow to fit within [0 1] before casting. How exactly you do that would depend on what the image data means in context and how subsequent operations are going to expect it to be scaled/centered.
If you don't care what the output class is, you could just multiply im*255, but bear in mind that some tools wouldn't know what to do with an image of that class and data range.
  3 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by