Reputation: 669
Why do Matplotlib load .png into float32 (from 0 to 1):
img = mpimg.imread('some.png')
print(img.dtype)
>>> float32
and .jpg to int8 (from 0 to 255):
img = mpimg.imread('some.jpg')
print(img.dtype)
>>> int8
Why? On the basis of what considerations is it realized this way?
Upvotes: 12
Views: 7896
Reputation: 37
In Matplotlib 3.xx, there is no read_png_int() method any more. But we can use following way to handle png file.
from PIL import Image
from numpy import asarray
test_pic="image.png"
image=Image.open(test_pic)
img=asarray(image)
print(img)
[[ 91 108 98]
[ 99 116 106]
[107 124 116]
...
[ 1 5 8]
[ 1 5 8]
[ 1 5 8]]
Upvotes: 2
Reputation: 339340
As the imread
documenation states:
matplotlib can only read PNGs natively, but if PIL is installed, it will use it to load the image and return an array (if possible) [...]
So for png
images, matplotlib has its own code to read the image, while for jpg
it relies on PIL
.
import matplotlib.pyplot as plt
im = plt.imread("house.png")
print im.dtype # float32
im = plt.imread("house.jpg")
print im.dtype # uint8
The internal _png
module which is responsible for loading the png
image, has two functions, read_png_float
and read_png_int
. While by default read_png_float
is used, you may as well manually use read_png_int
to obtain an integer image.
import matplotlib._png as png
im = png.read_png_float("house.png")
print im.dtype # float32
im = png.read_png_int("house.png")
print im.dtype # uint8
Finally, for a consistent behaviour you may use PIL
for both, png
and jpg
images instead of relying on matplotlib.
from PIL import Image
import numpy as np
im = np.asarray(Image.open("house.png"))
print im.dtype # uint8
im = np.asarray(Image.open("house.jpg"))
print im.dtype # uint8
Upvotes: 19