我怎么用PIL得到图片的尺寸?

2024-04-25 03:39:12 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

由于scipyimread已被弃用,请使用imageio.imread

  1. 安装-pip install imageio
  2. 使用height, width, channels = imageio.imread(filepath).shape
from PIL import Image

im = Image.open('whatever.png')
width, height = im.size

根据documentation

你可以用枕头(WebsiteDocumentationGitHubPyPI)。枕头与PIL有相同的接口,但是可以与Python 3一起使用。

安装

$ pip install Pillow

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

$ pip install --user Pillow

关于安装的其他注释是here

代码

from PIL import Image
with Image.open(filepath) as img:
    width, height = img.size

速度

这需要3.21秒来处理30336张图像(JPG从31x21到424x428,训练数据来自Kaggle上的National Data Science Bowl

这可能是用枕头代替自己写的东西的最重要原因。您应该使用枕头而不是PIL(python imaging),因为它与python 3一起工作。

备选方案1:纽比

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()

相关问题 更多 >