如何使用 PIL 或任何其他 Python 库获取图片边的大小?
from PIL import Image
im = Image.open('whatever.png')
width, height = im.size
根据文档。
您可以使用 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
这需要 3.21 秒来处理 30336 张图像(JPG 从 31x21 到 424x428,训练数据来自 Kaggle 上的National Data Science Bowl)
这可能是使用 Pillow 而不是自己编写的东西的最重要原因。你应该使用 Pillow 而不是 PIL (python-imaging),因为它适用于 Python 3。
scipy.ndimage.imread
,因为信息仍然存在,但请记住:
imread 已弃用! imread 在 SciPy 1.0.0 中已弃用,并在 1.2.0 中被删除。
import scipy.ndimage
height, width, channels = scipy.ndimage.imread(filepath).shape
import pygame
img = pygame.image.load(filepath)
width = img.get_width()
height = img.get_height()
由于
scipy
的 imread
已弃用,请使用 imageio.imread
。
pip install imageio
height, width, channels = imageio.imread(filepath).shape
这是一个完整的示例,从 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)
请注意,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]
以下是如何在 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
以下给出了尺寸和通道:
import numpy as np
from PIL import Image
with Image.open(filepath) as img:
shape = np.array(img).shape