MATLAB: Display an image changing its color

colorcolormapdigital image processingfigureimageimage analysisimage processing

Hi,
I want to display a white image during 10 seconds, changing its color to black every 1 second from white to black. My code is as follows:
% Create vector image
img = 255 * ones(1000, 1000, 3, 'uint8');
% Get handle of the image
handle = imshow(img);
% Experiment time = 10 seconds
a = tic;
while toc(a)<10
% Change color to white
handle.CData = 255 * ones(1000, 1000, 3, 'uint8');
% Display image

imshow(img);
b = tic;
% Wait 1 second until the change of color
while toc(b) < 1
end
% Change color to black
handle.CData = 0 * ones(1000, 1000, 3, 'uint8');
% Display image
imshow(img);
end
Sadly, no image is displayed during the 10 second while. The image is only displayed after the loop is over, so no change can be appreciated.
I would like to know where is my mistake.

Best Answer

There are a few things going on here that are affecting the display. First of all, I'm not entirely certain what you would like to see. Do you want the image to slowly transition from white to black? Do you want it to alternate between black and white every second?
The first issue is that you are modifying the CData of the original image (which is good), but you are using imshow multiple times (which is unnecessary and causes errors). imshow will create a new image, replacing your current image if "hold" is off. I would keep just the first call to imshow, and then only modify the CData after that.
Graphics operations in MATLAB are done on a lower priority thread than the code execution. If you want to force all the graphics operations queued up to execute before code continues, call drawnow. I would suggest doing this directly after you modify the CData.
You currently change the image to white at the beginning of the loop, wait for a second, then change it to black. But then the loop restarts and changes it immediately to white again. I think you meant to only change color once per loop. Or else put another pause after changing it to black.
Using something like:
b = tic;
while toc(b) < 1
end
will just eat processor. You may as well replace it with:
pause(1)
and free up the processor for other operations. Also:
0 * ones(1000, 1000, 3, 'uint8');
can be replaced with:
zeros(1000, 1000, 3, 'uint8');
Hope this helps!
-Cam