- Основные возможности библиотеки Python Imaging Library / Pillow / PIL
- Что такое Pillow?
- Загрузка и установка Pillow
- Убедитесь, что Pillow установлена
- Форматы файлов
- Как использовать Pillow для работы с изображениями
- Использование Pillow
- PIP Install PIL/Pillow – A Helpful Illustrated Guide
- How to Install Pillow on Windows?
- How to Install Pillow on Mac?
- How to Install Pillow on Linux?
- How to Install Pillow on Ubuntu?
- How to Install Pillow in PyCharm?
- How to Install Pillow in Anaconda?
- How to Install PIL in VSCode?
- Where to Go From Here?
- More Finxter Tutorials
- Programmer Humor
Основные возможности библиотеки Python Imaging Library / Pillow / PIL
PIL, известная как библиотека Python Imaging Library, может быть использована для работы с изображениями достаточно легким способом. У PIL не было никаких изменений и развития с 2009. Поэтому, добрые пользователи этого сайта предложили взглянуть на Pillow еще раз. Эта статья поможет вам узнать как пользоваться Pillow.
Что такое Pillow?
Pillow это форк PIL (Python Image Library), которая появилась благодаря поддержке Алекса Кларка и других участников. Основана на коде PIL, а затем преобразилась в улучшенную, современную версию. Предоставляет поддержку при открытии, управлении и сохранении многих форматов изображения. Многое работает так же, как и в оригинальной PIL.
Загрузка и установка Pillow
Перед началом использования Pillow, нужно загрузить и установить ее. Pillow доступна для Windows, Mac OS X и Linux. Самая “свежая” версия — это версия “8.1.0”, она поддерживается на python 3.6 и выше. Для установки Pillow на компьютеры Windows используйте conda или pip :
conda install -c anaconda pillow pip install Pillow
Для установки Pillow на компьютерах Linux просто используйте:
А установки Pillow на MacOS X нужно для начала установить XCode, а затем Homebrew. После того как Homebrew установлен, используйте:
$ brew install libtiff libjpeg webp littlecms $ sudo pip install Pillow
Убедитесь, что Pillow установлена
Убедитесь, что Pillow установлена, откройте терминал и наберите следующее в текущей строке:
$ python Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from PIL import Image
Если система показывает снова >>> , значит модули Pillow правильно установлены.
Форматы файлов
Перед началом использования модуля Pillow, давайте укажем некоторые поддерживаемые типы файлов: BMP, EPS, GIF, IM, JPEG, MSP, PCX PNG, PPM, TIFF, WebP, ICO, PSD, PDF . Некоторые типы файлов возможны только для чтения, в то время как другие доступны только для написания. Чтобы увидеть полный список поддерживаемых типов файла и больше информации о них, ознакомьтесь с руководством к Pillow.
Как использовать Pillow для работы с изображениями
Поскольку мы собираемся работать с изображениями, для начала, скачаем одно. Если у вас уже есть изображение, которое хотите использовать, пропустите этот шаг, описанный ниже.
В нашем примере будем использовать стандартное тестовое изображение под названием «Lenna» или «Lena». Это изображение используется во многих экспериментах по обработке изображений. Просто зайдите сюда и загрузите изображение. Если вы нажмете на изображение, оно сохранится как изображение с количеством пикселей 512×512.
Использование Pillow
Давайте посмотрим на возможные варианты использования этой библиотеки. Основные функции находятся в модуле Image . Вы можете создавать экземпляры этого класса несколькими способами. Путем загрузки изображений из файлов, обработки других изображений, либо создания изображений с нуля. Импортируйте модули Pillow, которые вы хотите использовать.
PIP Install PIL/Pillow – A Helpful Illustrated Guide
PIL is an abbreviation of Python Imaging Library and it adds image processing to Python.
In 2011, PIL has been discontinued—its unofficial successor framework Pillow for image processing is an actively maintained and user-friendly alternative in Python 3.
Alternatively, you may use any of the following commands to install pillow , depending on your concrete environment. One is likely to work!
💡 If you have only one version of Python installed:pip install pillow
💡 If you have Python 3 (and, possibly, other versions) installed:pip3 install
💡 If you don't have PIP or it doesn't workpillow
python -m pip install
💡 If you have Linux and you need to fix permissions (any one):pillow
python3 -m pip installpillow
sudo pip3 install
💡 If you have Linux with aptpillow
pip3 installpillow
--usersudo apt install
💡 If you have Windows and you have set up thepillow
py
aliaspy -m pip install
💡 If you have Anacondapillow
conda install -c anaconda
💡 If you have Jupyter Notebookpillow
!pip install
pillow
!pip3 install
pillow
Let’s dive into the installation guides for the different operating systems and environments!
How to Install Pillow on Windows?
To install the updated Pillow framework on your Windows machine, run the following code in your command line or Powershell:
Here’s the code for copy&pasting:
python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow
I really think not enough coders have a solid understanding of PowerShell. If this is you, feel free to check out the following tutorials on the Finxter blog.
Related Articles:
How to Install Pillow on Mac?
Open Terminal (Applications/Terminal) and run:
- xcode-select -install (You will be prompted to install the Xcode Command Line Tools)
- sudo easy_install pip
- sudo pip install pillow
- pip install pillow
As an alternative, you can also run the following two commands to update pip and install the Pillow library:
python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow
These you have already seen before, haven’t you?
Related Article:
How to Install Pillow on Linux?
To upgrade pip and install the Pillow library, you can use the following two commands, one after the other.
Here’s the code for copy&pasting:
python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow
How to Install Pillow on Ubuntu?
Upgrade pip and install the Pillow library using the following two commands, one after the other:
Here’s the code for copy&pasting:
python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow
How to Install Pillow in PyCharm?
The simplest way to install Pillow in PyCharm is to open the terminal tab and run the pip install Pillow command .
This is shown in the following code:
Here’s a screenshot of the two steps:
- Open Terminal tab in Pycharm
- Run pip install Pillow in the terminal to install Pillow in a virtual environment.
As an alternative, you can also search for Pillow in the package manager.
However, this is usually an inferior way to install packages because it involves more steps.
How to Install Pillow in Anaconda?
You can install the Pillow package with Conda using the command conda install -c anaconda pillow in your shell or terminal.
conda install -c anaconda pillow
This assumes you’ve already installed conda on your computer. If you haven’t check out the installation steps on the official page.
How to Install PIL in VSCode?
You can install PIL in VSCode by using the same command pip install pillow in your Visual Studio Code shell or terminal.
If this doesn’t work — it may raise a No module named ‘pillow’ error — chances are that you’ve installed it for the wrong Python version on your system.
To check which version your VS Code environment uses, run these two commands in your Python program to check the version that executes it:
import sys print(sys.executable)
The output will be the path to the Python installation that runs the code in VS Code.
Now, you can use this path to install pillow particularly for that Python version:
/path/to/vscode/python -m pip install pillow
Wait until the installation is complete and run your code using pillow again. It should work now!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
More Finxter Tutorials
Learning is a continuous process and you’d be wise to never stop learning and improving throughout your life. 👑
What to learn? Your subconsciousness often knows better than your conscious mind what skills you need to reach the next level of success.
I recommend you read at least one tutorial per day (only 5 minutes per tutorial is enough) to make sure you never stop learning!
💡 If you want to make sure you don’t forget your habit, feel free to join our free email academy for weekly fresh tutorials and learning reminders in your INBOX.
Also, skim the following list of tutorials and open 3 interesting ones in a new browser tab to start your new — or continue with your existing — learning habit today! 🚀
Python Basics:
Python Dependency Management:
Python Debugging:
Thanks for learning with Finxter!
Programmer Humor
❓ Question: How did the programmer die in the shower? ☠️
❗ Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: