我如何得到一个图片的大小与PIL或任何其他Python库?
当前回答
这是一个完整的例子,从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]
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()
以下给出了维度和渠道:
import numpy as np
from PIL import Image
with Image.open(filepath) as img:
shape = np.array(img).shape
由于scipy的imread已弃用,请使用imageio.imread。
Install - pip安装imageio 使用height, width, channels = imageio.imread(filepath).shape
推荐文章
- 2个数字表的余弦相似度
- 如何从熊猫的两列形成元组列
- 如何读一个文本文件到一个列表或数组与Python
- Django可选url参数
- 在matplotlib上为散点图中的每个系列设置不同的颜色
- 如何加载一个tsv文件到熊猫数据框架?
- 从csv文件创建字典?
- 如何在Python中将十六进制字符串转换为字节?
- set()是如何实现的?
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何使Python脚本在Linux中像服务或守护进程一样运行
- 返回大列表中每n项的python方式
- 如何使用Python中的DLL文件?
- 我如何量化两幅图像之间的差异?
- 获取列表列表到pandas DataFrame