Как узнать размер картинки python
Let us see how to find the resolution of an image in Python. We will be solving this problem with two different libraries which are present in Python:
- PIL
- OpenCV
In our examples we will be using the following image:
The resolution of the above image is 600×135.
Using PIL
We will be using a library named Pillow to find the size(resolution) of the image. We will be using the function PIL.Image.open() to open and read our image and store the size in two variables by using the function img.size.
Python3
Output:
Using OpenCV
We will import OpenCV by importing the library cv2. We will load the image using the cv2.imread() function. After this, the dimensions can be found using the shape attribute. shape[0] will give us the height and shape[1] will give us the width.
Получение и изменение размера изображения в Python
Чтобы получить размер изображения с помощью Pillow в Python, используйте свойство size объекта Image. Свойство size возвращает ширину и высоту изображения.
В этом уроке мы узнаем, как получить размер изображения, другими словами, ширину и высоту изображения, используя библиотеку Pillow.
Синтаксис
Синтаксис для использования свойства size объекта PIL Image приведен ниже.
Пример 1
В следующей программе мы будем читать и изображать, а затем распечатывать его размер, используя свойство size объекта Image.
Пример 2: доступ к ширине и высоте
Вы можете получить доступ к высоте и ширине из свойства size, используя index. В следующем примере мы получим ширину и высоту изображения.
В этом руководстве на примерах Python мы узнали, как получить размер изображения с помощью библиотеки Python Pillow с помощью хорошо подробных примеров программ.
Изменение размера изображения
Чтобы изменить размер изображения с помощью Pillow, вы можете использовать метод resize() класса PIL.Image.Image. Вы можете передать такие параметры, как размер результирующего изображения, фильтр передискретизации пикселей и область блока источника, которую необходимо учитывать.
Синтаксис
Синтаксис метода resize() показан в следующем фрагменте кода.
- size передается, как кортеж (ширина, высота). Это размер, запрошенный для результирующего выходного изображения после изменения размера.
- resample – это фильтр, который должен использоваться для повторной выборки, это необязательно. Вы можете пройти:
- PIL.Image.NEAREST;
- PIL.Image.BOX;
- PIL.Image.BILINEAR;
- PIL.Image.HAMMING;
- PIL.Image.BICUBIC;
- PIL.Image.LANCZOS.
Если для параметра размера заданы правильные значения, вы можете уменьшить или увеличить входное изображение.
Пример 1: со значениями по умолчанию
В следующем примере мы прочитаем изображение и изменим его размер до (200, 200).


Для изменения размера рассматривается все исходное изображение, поскольку мы не предоставили никакого значения для параметра box. В следующем примере мы предоставим параметр box и найдем выходное изображение.
Пример 2: с помощью поля входного изображения
В следующем примере мы предоставим параметр box. При этом мы рассматриваем только область поля входного изображения, а затем изменяем его размер до нужного размера.

Если вы заметили, для действия изменения размера учитывается только прямоугольная часть входного изображения.
В этом руководстве на примерах Python мы узнали, как изменить размер изображения с помощью библиотеки PIL.
Python Pillow – Get Image Size
To get the size of image using Python Pillow, use size property of Image object. The size property returns the width and height of the image.
In this tutorial, we shall learn how to get the size of image, in other words, width and height of an image, using Pillow library.
Syntax – Image.size
The syntax to use size property of PIL Image object is given below.
Example 1: Get Image Size
In the following program, we will read and image and then print its size using size property of the Image.
Python Program
Output
Example 2: Access Width and Height of Image using Index
You can access the height and width from size property using index. In the following example, we will get width and height of the image.
Python Program
Output
Summary
In this tutorial of Python Examples, we learned how to get the size of an image using Python Pillow library, with the help of well detailed example programs.
How do I get the picture size with PIL?
How do I get a size of a pictures sides with PIL or any other Python library?

7 Answers 7

You can use Pillow (Website, Documentation, GitHub, PyPI). Pillow has the same interface as PIL, but works with Python 3.
Installation
If you don’t have administrator rights (sudo on Debian), you can use
Other notes regarding the installation are here.
Speed
This needed 3.21 seconds for 30336 images (JPGs from 31×21 to 424×428, training data from National Data Science Bowl on Kaggle)
This is probably the most important reason to use Pillow instead of something self-written. And you should use Pillow instead of PIL (python-imaging), because it works with Python 3.
Alternative #1: Numpy (deprecated)
I keep scipy.ndimage.imread as the information is still out there, but keep in mind:
imread is deprecated! imread is deprecated in SciPy 1.0.0, and [was] removed in 1.2.0.