如何用PIL获取图片尺寸?

问题描述 投票:0回答:7

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

python python-imaging-library image
7个回答
785
投票
from PIL import Image

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

根据文档


111
投票

您可以使用 Pillow(网站文档GitHubPyPI)。 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

速度

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

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

替代方案#1:Numpy(已弃用)

我保留

scipy.ndimage.imread
,因为信息仍然存在,但请记住:

imread 已弃用! imread 在 SciPy 1.0.0 中已弃用,并在 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()

9
投票

由于

scipy
imread
已弃用,请使用
imageio.imread

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

4
投票

这是一个完整的示例,从 URL 加载图像,使用 PIL 创建,打印尺寸并调整大小......

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

2
投票

请注意,PIL 不会应用 EXIF 旋转信息(至少到 v7.1.1;在许多 jpg 中使用)。一个快速修复来适应这个:

def get_image_dims(file_path):
    from PIL import Image as pilim
    im = pilim.open(file_path)
    # returns (w,h) after rotation-correction
    return im.size if im._getexif().get(274,0) < 5 else im.size[::-1]

1
投票

以下是如何在 Python 3 中从给定 URL 获取图像大小:

from PIL import Image
import urllib.request
from io import BytesIO

file = BytesIO(urllib.request.urlopen('http://getwallpapers.com/wallpaper/full/b/8/d/32803.jpg').read())
im = Image.open(file)
width, height = im.size

0
投票

以下给出了尺寸和通道:

import numpy as np
from PIL import Image

with Image.open(filepath) as img:
    shape = np.array(img).shape
© www.soinside.com 2019 - 2024. All rights reserved.