Changing the output of the imread() function

When I use the imread function on a .tif file that I have done some processing with (specifically imagesc and export_fig to save it) it reads as a 640x480x3 matrix because it is seeing it as a truecolor image. Is there any way to have imread output it in a different way? I would like to have it be a 640x480 matrix if possible. If I need to provide anymore information let me know. Thanks in advance.

 Accepted Answer

Hey Seth,
Could you just use rgb2gray on the output of imread?
I = imread('mytiff.tif');
if size(I,3) == 3
I = rgb2gray(I);
end
Or if you'd like to retain the colors, but still keep the image as 640x480 for some reason, you could use rgb2ind to create an indexed image. You'll need to store the map output as well though to maintain color information.
-Cam

5 Comments

The only issue is the pixel intensity data has changed from when I exported and read it back in. I need it to be all the same so my data is consistent throughout.
Of course. If you go from 640x480x3 to 640x480, information is lost. If you don't want to lose or change the pixel color/intensity, then don't do anything to it. Why do you think you need to do this impossible thing anyway? For what purpose? You have the original image, so just keep it. Why create another image file that is essentially the same, unchanged information?
Another code that I had to run for the processing that I am doing wrote this image. When I read it back, it should be the same data as when it was written, correct? That is why I'm asking this. I'm trying to figure out why it is not the same when it's read as it was when it was written.
Who knows? I don't see that code for saving. What is should use is imwrite(), but again, why save just an exact copy of your original image when you still have the original image file?
In the most basic use-case, MATLAB is clearly able to write a black and white image to a TIF file, read it back in, and have it be the same:
I = imread('cameraman.tif');
size(I)
ans = 256 256
imwrite(I,'test.tif')
I2 = imread('test.tif');
isequal(I,I2)
So something must be different with your code. Are you providing any name-value pairs to either imread or imwrite? Like 'ColorSpace'?
Also, try sticking an:
assignin('base','imageBeforeWriting',I)
into the function that writes the image just before it's written. Then compare that to the image that is read in by the other function, just to make sure you're comparing apples to apples here.
If you are using export_fig, and not imwrite, to save it, then how do you know that it is supposed to be a NxMx1 image rather than an NxMx3 image?

Sign in to comment.

More Answers (0)

Categories

Find more on Images 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!