如何用PIL获取图片大小?
我怎么用PIL或者其他Python库来获取图片的边长呢?
7 个回答
9
因为 scipy
的 imread
已经不再推荐使用了,所以可以改用 imageio.imread
。
- 安装 - 运行
pip install imageio
来安装这个库。 - 使用 - 通过
height, width, channels = imageio.imread(filepath).shape
来获取图片的高度、宽度和通道数。
112
你可以使用Pillow(官网, 文档, GitHub, PyPI)。Pillow的使用方式和PIL一样,但它可以在Python 3中使用。
安装
$ pip install Pillow
如果你没有管理员权限(在Debian上是sudo),你可以使用
$ pip install --user Pillow
关于安装的其他说明可以在这里找到。
代码
from PIL import Image
with Image.open(filepath) as img:
width, height = img.size
速度
处理30336张图片(从31x21到424x428的JPG格式,训练数据来自国家数据科学杯在Kaggle上的数据)花费了3.21秒。
这可能是使用Pillow而不是自己写的代码的最重要原因。而且你应该使用Pillow而不是PIL(python-imaging),因为Pillow可以在Python 3中使用。
替代方案 #1: Numpy(已弃用)
我保留了scipy.ndimage.imread
的相关信息,因为这些信息仍然存在,但请记住:
imread已经被弃用了!在SciPy 1.0.0中,imread被标记为弃用,并在1.2.0中被移除。
import scipy.ndimage
height, width, channels = scipy.ndimage.imread(filepath).shape
替代方案 #2: Pygame
import pygame
img = pygame.image.load(filepath)
width = img.get_width()
height = img.get_height()
787
from PIL import Image
im = Image.open('whatever.png')
width, height = im.size
根据文档的说明。