'Convert PIL int32 to Float64

If I load a grayscale image with PIL:

>from PIL import Image
>import numpy as np
>
>img = Image.open('grayscale.png')

It will return as int32:

>np.array(img).dtype
dtype('int32')

And for the particular Image I got typical min and max Values:

>np.array(img).max()
65535
>np.array(img).min()
2580

But if I now cast the grayscale to rgb weird things are happen:

>casted_img = img.convert('RGB')
>np.array(casted_img).dtype
dtype('uint8')
>np.array(casted_img).max()
255
>np.array(casted_img).min()
255

It seems it just dumps the pixel values into uint8 loosing all entropy. So further converting to float64 doesn't makes any sense.

I have no issue doing the math myself, but I thought this is something already existing.

Or is PIL not the right tool for the job?



Solution 1:[1]

You can read the image as a float64 typed matrix like so:

from PIL import Image
import numpy as np

img = Image.open('grayscale.png')
img_matrix = np.array(img).astype(float64)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dudy_t