0

I am trying to open a .pgm image file in MATLAB, run a manipulation with a for loop and then save as another .pgm file. Before doing the manipulation I was testing to see if I could recreate the image:

clear

picture = imread('Picture.pgm');

sizePic = size(picture);

sizeX = sizePic(1);
sizeY = sizePic(2);

newPicture = zeros(sizeX,sizeY);


for i = 1:sizeX
    for j = 1:sizeY
        newPicture(i,j) = picture(i,j);
    end
end

imwrite(newPicture, 'NewPicture.pgm');

However, the new image is almost all white with some black splotches (not the original). Shouldn't this just give me back the original image?

1
  • Most likely has to do with the default encoding options in imread and imwrite. I would suggest checking documentation for the functions and then the encoding in your image file. Commented Aug 25, 2016 at 2:13

1 Answer 1

3

By default, picture created from imread(XXX.pgm) is either a uint8 or uint16 array, meaning the pixel values are in the range of [0 255] or [0 65535]. On the other hand, newPicture created from zeros is a double array, the expected pixel value for which is only [0 1]. Any value greater than 1 will be interpreted as 1 (white) in the saved image. When you assign a [0 255] value to such a double array, since most of the pixel values in picture is 1 and above, of course you will get mostly white pixels

When you work with images, always check the type of the image array. For example, it may be a good idea to always work with double type by explicitly converting the image returned by imread as such: pictures=im2double(imread(xxx)).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.