Работа с изображениями
Одной из популярных библиотек для работы с изображениями является Pillow . Формально эта библиотека является форком другой библиотеки — PIL (Python Imaging Library). Однако если PIL работала со 2-й версий Python и давно уже не развивается, то Pillow имеет поддержку 3-й версии и продолжает развиваться.
Итак, установим данную библиотеку с помощью следующей команды:
(Стоит отметить, что в некоторые дистрибутивы Linux данная библиотека уже включена по умолчанию)
Подключение
Для работы с библиотекой необходимо импортировать модуль Image :
Открытие изображения
Для открытия изображения вызывается функция open() , в которую передается путь к файлу:
В данном случае предполагается, что изображение представляет файл «forest.jpg» и располагается в одной папке с текущим скриптом Python. После выполнения функции переменная img будет содержать информацию об изображении в виде объекта класса Image (класс Image располагается в подключенном модуле Image).
На случай, если будет передан некорректный путь, и программа сгенерирует ошибку, можно поместить вызов метода в конструкцию try/catch :
Получение информации о файле
Класс Image предоставляет ряд атрибутов, которые хранят информацию об изображении:
filename : имя файла или путь к файлу в виде строки
format : формат файла. Если изображение создано самой библиотекой, то имеет значение None .
mode : режим изображения, например, «1», «L», «RGB» или «CMYK». (Полный список форматов доступен в документации)
size : размер в виде кортежа (width, height)
info : словарь dict, который хранит дополнительную ассоциированную с файлом информацию
is_animated : представляет булевое значение и равно True , если изображение содержит более одного фрейма. Применяется к анимированным изображениям
n_frames : количество фреймов в изображении. Применяется к анимированным изображениям
Например, получим некоторую информацию об изображении:
Консольный вывод в моем случае:
Вывод изображения на экран
С помощью метода show() можно октрыть изображение в программе для просмотра изображений по умолчанию для текщей операционной системы:
Сохранение изображения
Для сохранения изображения применяется метод save() . В качестве обязательного параметра он принимает путь, по которому сохраняется изображение:
Поворот изображения
Для вращения изображения применяется метод rotate() , в который в качестве обязательного параметра передается угол поворота. Результатом метода является повернутое изображение:

Обрезка изображения
Метод crop() позволяет вырезать часть изображения. В качестве параметра он принимает кортеж из 4 чисел, в формате:
Результатом метода является новое изображение:
В данном случае происходит обрезка, начиная с левого верхнего угла до его половины ширины и высоты.

Изменение размера
Для изменения размера изображения применяется метод resize() , в который в качестве параметра передается кортеж из двух чисел — новой высоты и ширины. Результатом метода является сгенерированное изображение. Например, уменьшим в два раза:
Если необходимо пропорциональное уменьшение размеров, то можно использовать метод reduce() , который в качестве обязательного параметра принимает множитель уменьшения. Например, уменьшим изображение в 2 раза:
Наложение изображения
Функция paste() позволяет наложить одно изображение на другое:
Первый параметр — im представляет второе изображение, которое будет накладываться. Параметр box определяет область наложения, а третий параметр — mask
В данном случае изображение «cats.jpg» накладывается на «forest.jpg». Поскольку область наложения не указана, то верхний левый угол «cats.jpg» проецируется на верхний левый угол «forest.jpg».
Параметр box позволяет определить область наложения либо в виде кортежа с двумя элементами (координаты X и Y верхнего левого угла), либо в виде кортежа с четырьмя элементами(координаты X и Y верхнего левого угла и правого нижнего угла):

Зеркальное отражение
Для зеркального отражения применяется метод transpose() . В качестве параметра он принимает принцип отзеркаливания в виде одного из следующих значений:
Как открыть картинку через Python?
![]()
Чтобы открыть картинку, используя приложение по умолчанию, на Windows:
Открыть наверное значит загрузить для показа (или обработки)? Если да то попробуйте через PIL, примерно так:
![]()
![]()
Попробуйте так (картинка откроется в веб-браузере):
![]()
![]()
Вы можете это сделать, например, с помощью специализированных библиотек для обработки изображений и обработки данных. opencv требует установки дополнительных пакетов. Но, при этом, позволяет, помимо прочего, широкий спектр возможностей для обработки изображений. Вторая matplotlib устанавливается легко, интегрируется в pyCharm и позволяет использовать довольно удобный встроенный интерфейс для просмотра. К сожалению, эта библиотека не предоставляет возможности для обработки изображений, а только для их визуализации.

Opencv
matplotlib:
matplotlib:

opencv: 
Установка opencv:
Флаг j указывает число процессов, которые будут использованы при установке
Установка matplotlib:
Если библиотека pillow не будет установлена, то можно будет пользоваться только * .png
Tutorial#
The most important class in the Python Imaging Library is the Image class, defined in the module with the same name. You can create instances of this class in several ways; either by loading images from files, processing other images, or creating images from scratch.
To load an image from a file, use the open() function in the Image module:
If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:
The format attribute identifies the source of an image. If the image was not read from a file, it is set to None. The size attribute is a 2-tuple containing width and height (in pixels). The mode attribute defines the number and names of the bands in the image, and also the pixel type and depth. Common modes are “L” (luminance) for greyscale images, “RGB” for true color images, and “CMYK” for pre-press images.
If the file cannot be opened, an OSError exception is raised.
Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate the image. For example, let’s display the image we just loaded:
The standard version of show() is not very efficient, since it saves the image to a temporary file and calls a utility to display the image. If you don’t have an appropriate utility installed, it won’t even work. When it does work though, it is very handy for debugging and tests.
The following sections provide an overview of the different functions provided in this library.
Reading and writing images#
The Python Imaging Library supports a wide variety of image file formats. To read files from disk, use the open() function in the Image module. You don’t have to know the file format to open a file. The library automatically determines the format based on the contents of the file.
To save a file, use the save() method of the Image class. When saving files, the name becomes important. Unless you specify the format, the library uses the filename extension to discover which file storage format to use.
Convert files to JPEG#
A second argument can be supplied to the save() method which explicitly specifies a file format. If you use a non-standard extension, you must always specify the format this way:
Create JPEG thumbnails#
It is important to note that the library doesn’t decode or load the raster data unless it really has to. When you open a file, the file header is read to determine the file format and extract things like mode, size, and other properties required to decode the file, but the rest of the file is not processed until later.
This means that opening an image file is a fast operation, which is independent of the file size and compression type. Here’s a simple script to quickly identify a set of image files:
Identify Image Files#
Cutting, pasting, and merging images#
The Image class contains methods allowing you to manipulate regions within an image. To extract a sub-rectangle from an image, use the crop() method.
Copying a subrectangle from an image#
The region is defined by a 4-tuple, where coordinates are (left, upper, right, lower). The Python Imaging Library uses a coordinate system with (0, 0) in the upper left corner. Also note that coordinates refer to positions between the pixels, so the region in the above example is exactly 300×300 pixels.
The region could now be processed in a certain manner and pasted back.
Processing a subrectangle, and pasting it back#
When pasting regions back, the size of the region must match the given region exactly. In addition, the region cannot extend outside the image. However, the modes of the original image and the region do not need to match. If they don’t, the region is automatically converted before being pasted (see the section on Color transforms below for details).
Here’s an additional example:
Rolling an image#
Or if you would like to merge two images into a wider image:
Merging images#
For more advanced tricks, the paste method can also take a transparency mask as an optional argument. In this mask, the value 255 indicates that the pasted image is opaque in that position (that is, the pasted image should be used as is). The value 0 means that the pasted image is completely transparent. Values in-between indicate different levels of transparency. For example, pasting an RGBA image and also using it as the mask would paste the opaque portion of the image but not its transparent background.
The Python Imaging Library also allows you to work with the individual bands of an multi-band image, such as an RGB image. The split method creates a set of new images, each containing one band from the original multi-band image. The merge function takes a mode and a tuple of images, and combines them into a new image. The following sample swaps the three bands of an RGB image:
Splitting and merging bands#
Note that for a single-band image, split() returns the image itself. To work with individual color bands, you may want to convert the image to “RGB” first.
Geometrical transforms#
The PIL.Image.Image class contains methods to resize() and rotate() an image. The former takes a tuple giving the new size, the latter the angle in degrees counter-clockwise.
Simple geometry transforms#
To rotate the image in 90 degree steps, you can either use the rotate() method or the transpose() method. The latter can also be used to flip an image around its horizontal or vertical axis.
Transposing an image#
transpose(ROTATE) operations can also be performed identically with rotate() operations, provided the expand flag is true, to provide for the same changes to the image’s size.
A more general form of image transformations can be carried out via the transform() method.
Color transforms#
The Python Imaging Library allows you to convert images between different pixel representations using the convert() method.
Converting between modes#
The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).
Image enhancement#
The Python Imaging Library provides a number of methods and modules that can be used to enhance images.
Filters#
The ImageFilter module contains a number of pre-defined enhancement filters that can be used with the filter() method.
Applying filters#
Point Operations#
The point() method can be used to translate the pixel values of an image (e.g. image contrast manipulation). In most cases, a function object expecting one argument can be passed to this method. Each pixel is processed according to that function:
Applying point transforms#
Using the above technique, you can quickly apply any simple expression to an image. You can also combine the point() and paste() methods to selectively modify an image:
Processing individual bands#
Note the syntax used to create the mask:
Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the second operand, and thus returns 0. Otherwise, it returns 255.
Enhancement#
For more advanced image enhancement, you can use the classes in the ImageEnhance module. Once created from an image, an enhancement object can be used to quickly try out different settings.
You can adjust contrast, brightness, color balance and sharpness in this way.
Enhancing images#
Image sequences#
The Python Imaging Library contains some basic support for image sequences (also called animation formats). Supported sequence formats include FLI/FLC, GIF, and a few experimental formats. TIFF files can also contain more than one frame.
When you open a sequence file, PIL automatically loads the first frame in the sequence. You can use the seek and tell methods to move between different frames:
Reading sequences#
As seen in this example, you’ll get an EOFError exception when the sequence ends.
The following class lets you use the for-statement to loop over the sequence:
Using the ImageSequence Iterator class#
PostScript printing#
The Python Imaging Library includes functions to print images, text and graphics on PostScript printers. Here’s a simple example:
Drawing PostScript#
More on reading images#
As described earlier, the open() function of the Image module is used to open an image file. In most cases, you simply pass it the filename as an argument. Image.open() can be used as a context manager:
If everything goes well, the result is an PIL.Image.Image object. Otherwise, an OSError exception is raised.
You can use a file-like object instead of the filename. The object must implement file.read , file.seek and file.tell methods, and be opened in binary mode.
Reading from an open file#
To read an image from binary data, use the BytesIO class:
Reading from binary data#
Note that the library rewinds the file (using seek(0) ) before reading the image header. In addition, seek will also be used when the image data is read (by the load method). If the image file is embedded in a larger file, such as a tar file, you can use the ContainerIO or TarIO modules to access it.
Reading from URL#
Reading from a tar archive#
Batch processing#
Operations can be applied to multiple image files. For example, all PNG images in the current directory can be saved as JPEGs at reduced quality.
Since images can also be opened from a Path from the pathlib module, the example could be modified to use pathlib instead of the glob module.
Controlling the decoder#
Some decoders allow you to manipulate the image while reading it from a file. This can often be used to speed up decoding when creating thumbnails (when speed is usually more important than quality) and printing to a monochrome laser printer (when only a greyscale version of the image is needed).
The draft() method manipulates an opened but not yet loaded image so it as closely as possible matches the given mode and size. This is done by reconfiguring the image decoder.
Reading in draft mode#
This is only available for JPEG and MPO files.
This prints something like:
Note that the resulting image may not exactly match the requested mode and size. To make sure that the image is not larger than the given size, use the thumbnail method instead.
5 Ways To Display Images in Python

In this article, we shall study the different ways how you can read and display images in Python. We can achieve this in numerous ways. The reason is due to the abundant library support. We will also explore how we can use them in crossbreeding with each other.
Ways to Display Images Using Python
The following is a list of libraries of Python that enable us to process the images and do the corresponding tasks.
- OpenCV
- Matplotlib
- Pillow
- Scikit-Image
- Tensorflow
Let’s now see how to display an image in a Python GUI window easily. There may be many other modules and/or hacks to view images too, so don’t limit yourself to just these 5 modules!
1. OpenCV to Display Images in Python
This is a very famous, beginner-friendly and open-source, and powerful package that is responsible for image processing. With a small set of commands, we can take our Computer Vision journey to next level. There are two main functions OpenCV provides to read and display images.
- cv2.imread()
- cv2.imshow()
Code:
Output:

Displaying the image through OpenCV
Explanation:
- Import the OpenCV package to access the functions. Also, import the sys module for additional packages.
- Create a variable as img that holds our image. Call the cv2.imread() function and deliver the image path/image name as a first parameter. Then set the cv2.IMREAD_ANYCOLOR is the next parameter to read every color of the image.
- Then set a while loop and that will help us render the image an infinite number of times till we exit the system.
- Then use the cv2.imshow() function inside the while loop. It takes two parameters, the image title and the image path variable img.
- The cv2.waitkey() method waits till we exit or click on the close button.
- Then call the sys.exit() method to safely exit the technique.
- Finally, we destroy all the created windows using cv2.destroyAllWindows().
2. Matplotlib
This package is mainly for data visualization. But, through the plotting techniques, we can view the image in a graphical format where each pixel lies on 2D x-y axes.
Thie library also has the equivalent functions as that of open cv. Just the package name changes.
- matplotlib.image.imread()
- matplotlib.pyplot.imshow()
Code:
Output:

Displaying image through Matplotlib
Explanation:
- Import the Matplotlib packages’ pylot and image modules.
- Set the title of the image as Sheep Image using plt.title() method.
- As matplotlib reads the image in x-y plane. We need labels xlabel() and ylabel() functions to mention the axes and the pixels.
- Create a variable as an image that holds our image. Call the mpimg.imread() function and give the image path/imagename as a first parameter.
- Then set a while loop and that will help us render the image an infinite number of times till we exit the system.
- Then use the plt.imshow() function that takes image variable img. But it will show it in the backend.
- To view it on the screen use the plt.show() method and we have our image with properly scaled parameters on the screen.
3. Pillow
This library often offers simple methods for Image manipulations. We can say that it is an image-only library because of its simplicity and adaptability. The functions we are gonna using are open() and show() from PILLOW’s Image module. This action is just within three lines of code.
Code:
Output:

Displaying image through PILLOW
Explanation:
- Import the module Image from PIL.
- Create a variable img and then call the function open() in it. Give the path that has the image file.
- Call the show() function in joint with img variable through the dot operator “.”.
- It displays the image through the built-in Photo app in your respective OS.
4. Scikit-Image
Scikit-Image is a sub-module of Scikit-Learn. It is built upon Python and supportive library Matplotlib thus it derives some of its functionalities. Methods are similar to that of the previous packages we saw before.
Code:
Output:

Displaying image through Skimage
5. Tensorflow
This is a powerful Machine Learning library especially from Google.Inc. It works on different aspects of Machine Learning, Deep Learning, and related concepts. It also has built-in datasets to start a hassle-free journey of Data Science and ML engineering. It works specifically on the computer’s GPU CUDA cores. This makes the model training more efficient and gives less stress to the CPU.
We will be using this library in joint with the Matplotlib module. Because this makes image plotting and displaying much easier.
Code:
Explanation:
- Import TensorFlow. Then from TensorFlowalso import io and image.
- Import matplotlib’s pyplot module for plotting purposes.
- (Optional) also, use the warnings package to avoid unnecessary warnings.
- Create a TensorFlow image variable “tf_img” and call the io.read_file() method. Give the image path inside it.
- It is read as a default file. To view it as the image we need to use the decode_png() function from the image to get recognized by the system. Make sure you use the correct decider function. They are different for each image type. Use channels = 3. for default GPU usage.
- Finally, display the captured image through the plt.imshow() method.
Output:

Displaying Image through Tensorflow and Matplotlib
Conclusion
So, these are the different considerable ways through which we can perform image processing. Python has a ton of options for each unique task. Comment down which method and library do you like the most we implemented in this article.