Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers)
PythonMatplotlibNormalizationPython Problem Overview
I tried to run the graph cut algorithm for a slice of an MRI after converting it into PNG format. I keep encountering the following problem:
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
This is even after setting vmin
and vmax
as follows:
plt.imshow(out, vmin=0, vmax=255)
Python Solutions
Solution 1 - Python
Cast the image to np.uint8
after scaling [0, 255]
range will dismiss this warning. It seems like a feature in matplotlib
, as discussed in this issue.
plt.imshow((out * 255).astype(np.uint8))
Solution 2 - Python
Instead of plt.imshow(out)
, use plt.imshow(out.astype('uint8'))
. That's it!
Solution 3 - Python
If you want to show it, you can use img/255
.
Or
np.array(img,np.int32)
The reason is that if the color intensity is a float, then matplotlib expects it to range from 0 to 1. If an int, then it expects 0 to 255. So you can either force all the numbers to int or scale them all by 1/255.
Solution 4 - Python
As the warning is saying, it is clipping the data in between (0,1).... I tried above methods the warning was gone but my images were having missing pixel values. So I tried following steps for my numpy array Image (64, 64, 3). Step 1: Check the min and max values of array by
maxValue = np.amax(Image)
minValue = np.amin(Image)
For my case min values of images were negative and max value positive, but all were in between about (-1, 1.5) so Step 2: I simply clipped the data before imshow by
Image = np.clip(Image, 0, 1)
plt.imshow(Image)
Note if your pixel values are ranged something like (-84, 317) etc. Then you may use following steps
Image = Image/np.amax(Image)
Image = np.clip(Image, 0, 1)
plt.imshow(Image)
Solution 5 - Python
Simply make it within this range [0:1]
if it is between [-1, 1] after calling the amax() and amin() then
img = img / 2 + 0.5
if it is between [0, 250]
img = img / 250