我如何得到一个图片的大小与PIL或任何其他Python库?
当前回答
注意,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
注意,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]
from PIL import Image
im = Image.open('whatever.png')
width, height = im.size
根据文档。
你可以使用枕头(网站,文档,GitHub, PyPI)。Pillow具有与PIL相同的界面,但与Python 3一起工作。
安装
$ pip install Pillow
如果您没有管理员权限(Debian上的sudo),您可以使用
$ pip install --user Pillow
关于安装的其他注意事项在这里。
Code
from PIL import Image
with Image.open(filepath) as img:
width, height = img.size
速度
30336张图片需要3.21秒(jpg格式从31x21到424x428,训练数据来自Kaggle上的国家数据科学碗)
这可能是使用Pillow而不是自己编写的东西的最重要原因。您应该使用Pillow而不是PIL (Python -imaging),因为它适用于Python 3。
替代方案#1:Numpy(已弃用)
我保留scipy. nmage .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()
推荐文章
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?