Python pil rotate image

Как повернуть изображение используя Pillow

Поворачиваем изображение в PIL Python

Метод rotate() из модуля Image применяется для поворачивания изображения в зависимости от указанных градусов.

Загружаем и сохраняем картинку: guido-van-rossum.jpg

Данный код выведет наше изображение.

Как повернуть изображение используя Pillow

Угол вращения картинки в Pillow

В методе rotate() указываем угол вращения изображения в градусах в качестве первого аргумента. Направление вращения будет против часовой стрелки.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Поворачиваем изображение на 90 градусов:

Полученный результат с повернутой картинкой на 90 градусов против часовой стрелки:

Повернуть картинку на 90 градусов

Поворачиваем изображение на 45 градусов через PIL в Python:

Поворачиваем изображение на 45 градусов

Поворачиваем изображение полностью

Как видно на картинках в примерах выше, по умолчанию размер готового изображения равен размеру изначального изображения, а части повернутого изображения которые попали за пределами изначального размера отсекаются. Если мы поставим параметр expand на True , то повернутое изображение удовлетворит наши требования.

Теперь изображение выглядит так как мы ожидали. Она повернулась полностью, без черных границ по сторонам.

Поворачиваем изображение на 90 градусов

Поворачиваем изображение на 45 градусов.

Поворачиваем изображение на 45 градусов в Python

Фильтры NEAREST, BILINEAR и BICUBIC в Pillow

Параметр resample можно использовать для указания определенного фильтра, который будет использоваться при поворачивании изображения.

С помощью фильтра Image.BICUBIC детали изображения станут более четким, чем в случае использования фильтра по умолчанию Image.NEAREST .

Image.NEAREST Image.BILINEAR Image.BICUBIC
Pillow Image.NEAREST Python PIL Image.BILINEAR Python Pillow Image.BICUBIC Python

Небольшие различия есть, но у данной картинки они не очень видны. Но, например фильтр Image.BILINEAR сделал картинку более гладкой.

Меняем центр изображения при её поворачивании

Вы можете уточнить позицию центра изображения с помощью параметра center в методе rotate() .

Источник

Python Pillow – Rotate Image 45, 90, 180, 270 degrees

To rotate an image by an angle with Python Pillow, you can use rotate() method on the Image object. rotate() method rotates the image in counter clockwise direction.

In this tutorial, we shall learn how to rotate an image, using PIL Python library, with the help of example programs.

Syntax of PIL Image.rotate()

The syntax of rotate() method is as shown in the following code block.

Image.rotate(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None)
  • angle – In degrees counter clockwise.
  • resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation in a 2×2 environment), or PIL.Image.BICUBIC (cubic spline interpolation in a 4×4 environment). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST. See Filters.
  • expand – Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation.
  • center – Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image.
  • translate – An optional post-rotate translation (a 2-tuple).
  • fillcolor – An optional color for area outside the rotated image.

Examples

1: Rotate given image by 45 degrees

In the following example, we will rotate the image by 45 degrees in counter clockwise direction.

Python Program

from PIL import Image #read the image im = Image.open("sample-image.png") #rotate image angle = 45 out = im.rotate(angle) out.save('rotate-output.png')

Input Image – sample-image.png

Python Pillow - Rotate Image

Output Image – rotate-image.png

Python Pillow – Rotate Image 45, 90, 180, 270 degrees

The size of the original image is preserved. You can make the size of the output image adjust to the rotation.

2. Rotate image and adjust the output size

In the following example, we will adjust the size of output image to the rotation, by using the parameter expand=True.

from PIL import Image #read the image im = Image.open("sample-image.png") #rotate image angle = 45 out = im.rotate(angle, expand=True) out.save('rotate-output.png')

Python Pillow – Rotate Image 45, 90, 180, 270 degrees

3. Rotate image by 90 degrees

You can rotate an image by 90 degrees in counter clockwise direction by providing the angle=90. We also give expand=True, so that the rotated image adjusts to the size of output.

from PIL import Image #read the image im = Image.open("sample-image.png") #rotate image by 90 degrees angle = 90 out = im.rotate(angle, expand=True) out.save('rotate-output.png')

Python Pillow – Rotate Image 45, 90, 180, 270 degrees

4. Rotate image by 180 degrees

In this Python Pillow example, we will rotate the image by 180 degrees.

from PIL import Image #read the image im = Image.open("sample-image.png") #rotate image by 180 degrees angle = 180 out = im.rotate(angle, expand=True) out.save('rotate-output.png')

Python Pillow – Rotate Image 45, 90, 180, 270 degrees

Summary

Concluding this tutorial of Python Examples, we learned how to rotate an image using Python PIL library.

Источник

Читайте также:  Загрузка файла
Оцените статью