sam
sam

Reputation: 75

misc.imread and misc.imsave changes pixel values

I am:

When I reopen the image I see different pixel values.

My code snippet:

image = misc.imread('lena.jpg')  
maximum = np.max(image) # finds maximum pixel value of image  
img = np.divide(image, maximum) # divide every pixel value by maximum
# scale every pixel value between 0 and 127
img_scale = np.round(img * (np.power(2,7)-1)).astype(int)  
misc.imsave('lena_scaled.jpg', img_scale)  
img_reopen = misc.imread('lena_scaled.jpg')

When I compare img_scale and img_reopen I get different values:

By executing np.max(img_scale), I get 127.
By executing np.max(img_reopen), I get 255
By executing img_scale[0][0], I get [82,82,82]
By executing img_reopen[0][0], I get [156][156][156]

Question

Why do the pixel values get changed after saving the image and reopening it?

Upvotes: 0

Views: 620

Answers (1)

Bussller
Bussller

Reputation: 2011

The imsave function rescales the image when it saves to the disk.

misc.imsave function uses bytescale under the hood to rescale image to the full range (0,255).

That's why you get np.max 255 when you reopen. Please refer to the documentation here.

Follow-up: To preserve your values without rescaling, you can try use misc.toimage function and save the resulting as follows,

im = misc.toimage(img_scale, high=np.max(img_scale), low=np.max(img_scale)
im.save('lena_scaled.jpg')

When you read the 'lena_scaled.jpg' with misc.imsave you can try use the following:

misc.imread('lena_scaled.jpg', mode='I')

I - ‘L’ (8-bit pixels, black and white) which I believe would work for your grayscale image.

Hope this helps.

Upvotes: 1

Related Questions