如何使用PIL获得图片大小?

I15*_*159 228 python image python-imaging-library

如何使用PIL或任何其他Python库获得图片大小?

phi*_*mue 405

from PIL import Image

im = Image.open('whatever.png')
width, height = im.size
Run Code Online (Sandbox Code Playgroud)

根据文件.

  • 如果你也想知道通道的数量,你应该使用```im.mode```.既然PIL有点神秘,你也可以使用numpy:````numpy.array(im).shape``` (3认同)
  • 注意@AlexKreimer使用`.shape`会导致不同的返回值,因为height是2d数组的第一个,然后是width。因此`height,width = np.array(im).shape` (3认同)
  • 请使用“with”。 (3认同)
  • 值得注意的是,“Image.open()”读取元数据而不加载完整图像,这可能有优点(更快)或缺点(重复),具体取决于您的用例。使用“Image.load()”读取完整图像。/sf/answers/1332445971/ (2认同)

Mar*_*oma 68

您可以使用Pillow(网站,文档,GitHub,PyPI).Pillow与PIL具有相同的界面,但与Python 3一起使用.

安装

$ pip install Pillow
Run Code Online (Sandbox Code Playgroud)

如果您没有管理员权限(Debian上的sudo),您可以使用

$ pip install --user Pillow
Run Code Online (Sandbox Code Playgroud)

有关安装的其他说明在这里.

from PIL import Image
with Image.open(filepath) as img:
    width, height = img.size
Run Code Online (Sandbox Code Playgroud)

速度

30336张图像需要3.21秒(JPG从31x21到424x428,来自Kaggle 国家数据科学碗的训练数据)

这可能是使用Pillow而不是自编的最重要原因.你应该使用Pillow代替PIL(python-imaging),因为它适用于Python 3.

备选方案#1:Numpy

import scipy.ndimage
height, width, channels = scipy.ndimage.imread(filepath).shape
Run Code Online (Sandbox Code Playgroud)

备选方案#2:Pygame

import pygame
img = pygame.image.load(filepath)
width = img.get_width()
height = img.get_height()
Run Code Online (Sandbox Code Playgroud)


blu*_*ers 8

由于scipy'simread已被弃用,请使用imageio.imread.

  1. 安装 - pip install imageio
  2. height, width, channels = imageio.imread(filepath).shape