我如何得到一个图片的大小与PIL或任何其他Python库?
当前回答
你可以使用枕头(网站,文档,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
你可以使用枕头(网站,文档,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()
from PIL import Image
im = Image.open('whatever.png')
width, height = im.size
根据文档。
由于scipy的imread已弃用,请使用imageio.imread。
Install - pip安装imageio 使用height, width, channels = imageio.imread(filepath).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]