gpt4 book ai didi

python - Matplotlib 将 jpg 读入 int8 并将 png 读入规范化的 float

转载 作者:行者123 更新时间:2023-11-28 22:24:55 25 4
gpt4 key购买 nike

为什么 Matplotlib 将 .png 加载到 float32(从 0 到 1):

img = mpimg.imread('some.png')
print(img.dtype)
>>> float32

和 .jpg 到 int8(从 0 到 255):

img = mpimg.imread('some.jpg')
print(img.dtype)
>>> int8

为什么?这样做是基于什么考虑?

最佳答案

作为imread documenation状态:

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) [...]

所以对于png图片,matplotlib有自己的读取图片的代码,而对于jpg则依赖于PIL

import matplotlib.pyplot as plt

im = plt.imread("house.png")
print im.dtype # float32

im = plt.imread("house.jpg")
print im.dtype # uint8

内部_png模块负责加载png图片,有两个函数,read_png_floatread_png_int。虽然默认使用 read_png_float,但您也可以手动使用 read_png_int 来获取整数图像。

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

最后,为了保持一致的行为,您可以对 pngjpg 图像使用 PIL,而不是依赖 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

关于python - Matplotlib 将 jpg 读入 int8 并将 png 读入规范化的 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46013594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com