Answer a question

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?

Answers

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
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐