Reputation: 77
First I scale a RGB image to [0,1], then it is ok showed in matplotlib.
Then I recover it (by times 255), and show it, but it became purple, as shown in the pictures I paste below.
What is the reason? How to solve it? What is the correct way to rescale a image to [0,255]?
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
dog = mpimg.imread('1.jpg')
dog = dog / 255
plt.subplot(121)
plt.imshow(dog) #Normal and ok here
plt.title(('/255'))
dog = dog*255
plt.subplot(122)
plt.imshow(dog) # Purple image, not ok
plt.title('*255')
plt.savefig('out.jpg')
plt.show()
=============================a line here==========================
Suggested by @BruceWayne, I try to *-255 instead of *255, and it works.
But what is the reason? Why would a picture with values in [-255, 0] showed normal, and one with [0,255] go different way?
Upvotes: 0
Views: 1593
Reputation: 6786
When I tried your program, I got a warning saying "Clipping input data to the valid range for imshow with RGB data ([0..1] for float or [0..255] for integers)."
When you first load the image, it is made up from integers in the 0..255 range, which imshow displays normally. When you divide this by 255, it turns into floats in the [0..1] range which, again, imshow displays normally.
Then you multiply by 255, turning it into floats in the [0..255] range, and this imshow does not know what to do with!
I tried changing it back into integers using
import numpy as np
dog = (dog * 255).astype(np.uint8)
(there's probably some better way of doing that) and then it displays normally again.
Upvotes: 2