3
votes

It is an interesting problem.

>> img = imread('a.pgm')
>> size(img)
ans

   192 168

>> imshow(img) % works fine

However, I am copying the same matrix to temp and trying to imshow again. Does not work properly.

temp = zeros(192,168)
for i=1:192
   for j=1:168
      temp(i,j) = img(i,j)
   endfor
endfor

imshow(temp) % it is an empty image

Why?

1
If you just wanted to copy the matrix, temp = img is the "correct" way to do it in MATLAB / Octave. - Stewie Griffin

1 Answers

5
votes

The reason is because when you do

 temp = zeros(192,168)

MATLAB allocates a matrix of double. So even if you put uint8 into the matrix, the format of the matrix temp will be double until you don't cast it to unit8.

The reason why it is white, is because MATLAB when dealing with double images expects intensity in the range [0....1]. Everything that is over 1 (as in your case everything, but the 0s) is clamped to 1, the maximum intensity, that obviously means white.

You can solve it by either casting the initial matrix to

temp = uint8(zeros(192,168))

or at the end

temp = uint8(temp)

or again only for displaying purposes inside the imshow call:

imshow(uint8(temp))

Also in general, as correctly point out by @Robert P. in the comments, the proper way to copy an image would have been simply temp = img