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?
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))
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.