Modulenotfounderror no module named pil windows

I use this command in the shell to install PIL: easy_install PIL then I run python and type this: import PIL. But I get this error: Traceback (most recent call last): File "", l...

I use this command in the shell to install PIL:

easy_install PIL

then I run python and type this: import PIL. But I get this error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
ImportError: No module named PIL

I’ve never had such problem, what do you think?

Eric O Lebigot's user avatar

asked Jan 14, 2012 at 17:24

Asma Gheisari's user avatar

Asma GheisariAsma Gheisari

5,4549 gold badges29 silver badges51 bronze badges

5

In shell, run:

pip install Pillow

Attention: PIL is deprecated, and pillow is the successor.

sehe's user avatar

sehe

364k47 gold badges440 silver badges616 bronze badges

answered Mar 28, 2014 at 20:49

zhiming wang's user avatar

6

On some installs of PIL, you must do

import Image

instead of import PIL (PIL is in fact not always imported this way). Since import Image works for you, this means that you have in fact installed PIL.

Having a different name for the library and the Python module is unusual, but this is what was chosen for (some versions of) PIL.

You can get more information about how to use this module from the official tutorial.

PS: In fact, on some installs, import PIL does work, which adds to the confusion. This is confirmed by an example from the documentation, as @JanneKarila found out, and also by some more recent versions of the MacPorts PIL package (1.1.7).

answered Jan 14, 2012 at 17:36

Eric O Lebigot's user avatar

Eric O LebigotEric O Lebigot

89.4k48 gold badges215 silver badges259 bronze badges

12

On a different note, I can highly recommend the use of Pillow which is backwards compatible with PIL and is better maintained/will work on newer systems.

When that is installed you can do

import PIL 

or

from PIL import Image

etc..

kba's user avatar

kba

1,0579 silver badges20 bronze badges

answered Jul 23, 2013 at 9:24

Damian's user avatar

DamianDamian

2,55822 silver badges19 bronze badges

1

This worked for me on Ubuntu 16.04:

sudo apt-get install python-imaging

I found this on Wikibooks after searching for about half an hour.

answered Nov 17, 2016 at 14:56

grooveplex's user avatar

grooveplexgrooveplex

2,4514 gold badges28 silver badges30 bronze badges

4

Sometimes I get this type of error running a Unitest in python. The solution is to uninstall and install the same package on your virtual environment.

Using this commands:

pip uninstall PIL

and

pip install  PIL 

If for any reason you get an error, add sudo at the beginning of the command and after hitting enter type your password.

Anshul Goyal's user avatar

Anshul Goyal

70.8k37 gold badges145 silver badges178 bronze badges

answered Feb 25, 2013 at 15:01

Fernando Munoz's user avatar

Fernando MunozFernando Munoz

4,3512 gold badges18 silver badges16 bronze badges

4

you have to install Image and pillow with your python package.

type

python -m pip install image 

or run command prompt (in windows), then navigate to the scripts folder

cd C:Python27Scripts

then run below command

pip install image

answered Jan 2, 2018 at 13:18

azdoud's user avatar

azdoudazdoud

1,2099 silver badges17 bronze badges

2

On windows 10 I managed to get there with:

cd "C:Users<your username>AppDataLocalProgramsPythonPython37-32" 
python -m pip install --upgrade pip     <-- upgrading from 10.something to 19.2.2.
pip3 uninstall pillow
pip3 uninstall PIL
pip3 install image

after which in python (python 3.7 in my case) this works fine…

import PIL
from PIL import image

answered Aug 20, 2019 at 20:11

andrew pate's user avatar

andrew pateandrew pate

3,67734 silver badges26 bronze badges

1

I used:

pip install Pillow 

and pip installed PIL in Libsite-packages. When I moved PIL to Lib everything worked fine. I’m on Windows 10.

answered Aug 5, 2019 at 0:45

cromastro's user avatar

cromastrocromastro

1611 silver badge4 bronze badges

Install Specific Version:

pip install Pillow

Upgrade Pillow

sudo pip3 install --upgrade Pillow

Getting Dependency Error in Window 10
Use code: easy_install instead of pip install

easy_install Pillow 

Upgrade using easy install

sudo easy_install --upgrade  Pillow

On OSX System to install Module:
Use code: brew install instead of pip install

brew install Pillow 

Without Using Pip :

 sudo apt-get install -y Pillow 

On CentOS7 or Linux Fedora:

yum -y install Pillow 

Or on Fedora try

sudo dnf install Pillow 

Command if Homebrew screws up your path on macOS:

python -m pip install Pillow 

For Python3 MacOs Homebrew screws

python3 -m pip install Pillow

Verify module from list MacOs

pip freeze | grep  Pillow

For Execute on Anaconda as your python package manager

 conda install -c anaconda Pillow 

answered Mar 27, 2021 at 7:33

Shantanu Bombatkar's user avatar

1

On windows, try checking the path to the location of the PIL library. On my system, I noticed the path was

Python26Libsite-packagespil instead of Python26Libsite-packagesPIL  

after renaming the pil folder to PIL, I was able to load the PIL module.

Robert's user avatar

Robert

5,26743 gold badges65 silver badges115 bronze badges

answered Apr 4, 2013 at 11:08

Komla's user avatar

KomlaKomla

811 silver badge1 bronze badge

1

if you use anaconda:

conda install pillow

answered Jan 10, 2018 at 23:02

Conor Cosnett's user avatar

Conor CosnettConor Cosnett

1,0511 gold badge14 silver badges19 bronze badges

2

You will need to install Image and pillow with your python package.
Rest assured, the command line will take care of everything for you.

Hit

python -m pip install image

answered May 10, 2017 at 8:43

Dipanshu Sehjal's user avatar

instead of PIL use Pillow it works

easy_install Pillow

or

pip install Pillow

answered Apr 13, 2018 at 5:21

saigopi.me's user avatar

saigopi.mesaigopi.me

13k2 gold badges79 silver badges54 bronze badges

I had the same issue on windows 10 and this worked for me:

pip install Pillow

answered Mar 7, 2022 at 8:51

Cyebukayire's user avatar

CyebukayireCyebukayire

7407 silver badges14 bronze badges

pip(3) uninstall Pillow
pip(3) uninstall PIL
pip(3) install Pillow

answered Oct 15, 2020 at 16:34

Newt's user avatar

NewtNewt

7298 silver badges14 bronze badges

The cleanest way to resolve this issue is by following below steps.

Step 1: Uninstall the PIL package.

pip uninstall PIL

Step 2: Install the Pillow using pip as shown below on windows operating systems. For other environments checkout the article No module named PIL

On Windows

python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow

Step 3: The most crucial class in the Python Imaging Library is the Image class, and you can import this as shown below.

from PIL import Image
im = Image.open("myimage.jpg")

If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:

print(im.format, im.size, im.mode)

#Output: PPM (512, 512) RGB

answered Dec 9, 2021 at 18:25

Srinivas Ramakrishna's user avatar

This worked for me on Ubuntu 20.04:

pip install image

And in script:

import image

answered Sep 24, 2022 at 13:33

MD. Mohiuddin Ahmed's user avatar

use pil instead of PIL

from pil import Image

answered Sep 5, 2020 at 13:58

Newt's user avatar

NewtNewt

7298 silver badges14 bronze badges

I used conda-forge to install pillow version 5, and that seemed to work for me:

conda install --channel conda-forge pillow=5

the normal conda install pillow did NOT work for me.

answered Jul 10, 2018 at 16:06

Geoff Perrin's user avatar

Geoff PerrinGeoff Perrin

4141 gold badge6 silver badges13 bronze badges

I had the same problem and i fixed it by checking what version pip (pip3 --version) is, then realizing I’m typing python<uncorrect version> filename.py instead of python<correct version> filename.py

answered Dec 23, 2018 at 23:24

Ori Barmatz's user avatar

I used :

from pil import Image

instead of

from PIL import Image

and it worked for me fine

wish you bests

answered Jul 20, 2020 at 10:12

Heydar's user avatar

HeydarHeydar

1378 bronze badges

I had the same issue while importing PIL and further importing the ImageTk and Image modules. I also tried installing PIL directly through pip. but not success could be achieved. As in between it has been suggested that PIL has been deprectaed, thus, tried to install pillow through pip only. pillow was successfully installed, further, the PIL package was made under the path : python27/Lib/site-packages/.

Now both Image and ImageTk could be imported.

answered May 25, 2015 at 16:47

Prateek Jain's user avatar

I recently installed Leap. I Tried openshot and it didn’t start. So came here and found a suggestion to start from the Terminal to see if there were any error.

The error I had was error missing mlt. So I installed the python-mlt module from Yast and imported it, tried to start but next openshot said missing pil.

I Followed the Pillow suggestion to install because Yast couldn’t find any pil and imported pil. That went ok but did not start and showed Error missing goocanvas.

The I installed goocanvas with Yast, imported it in python, and Openshot fired up !!

With a lot of errors in the terminal like missing Vimeoclient and lots of attributeerrors. Well, will see if it is of any influence working with it.

Thomasleveil's user avatar

Thomasleveil

90.2k14 gold badges117 silver badges109 bronze badges

answered Jan 9, 2016 at 15:20

Johan's user avatar

Python 3.8 on Windows 10. A combination of the answers worked for me. See below for a standalone working example. The commented out lines should be executed in the command line.

import requests
import matplotlib.pyplot as plt
# pip uninstall pillow
# pip uninstall PIL
# pip install image
from PIL import Image
url = "https://images.homedepot-static.com/productImages/007164ea-d47e-4f66-8d8c-fd9f621984a2/svn/architectural-mailboxes-house-letters-numbers-3585b-5-64_1000.jpg"
response = requests.get(url, stream=True)
img = Image.open(response.raw)
plt.imshow(img)
plt.show()

answered Sep 22, 2020 at 23:46

Jortega's user avatar

JortegaJortega

3,4261 gold badge18 silver badges21 bronze badges

I had the same issue and tried many of the solutions listed above.

I then remembered that I have multiple versions of Python installed AND I use the PyCharm IDE (which is where I was getting this error message), so the solution in my case was:

In PyCharm:

go to File>Settings>Project>Python Interpreter

click «+» (install)

locate Pillow from the list and install it

Hope this helps anyone who may be in a similar situation!

answered Oct 28, 2020 at 18:33

Goob-The-Noob's user avatar

I found an easier solution. Use a virtual environment.

pip install Pillow
from PIL import Image

This works for me on a macOS

answered Oct 31, 2021 at 21:14

Thesonter's user avatar

According to the official websiteInstall Pillow, you may want to try this:

go to Terminal and run:

  • python3 -m pip install --upgrade pip

Then Run on

  • source ~/.bash_profile

answered Nov 22, 2021 at 9:35

Mohamed Berrimi's user avatar

You are probably missing the python headers to build pil. If you’re using ubuntu or the likes it’ll be something like

apt-get install python-dev

answered Jan 14, 2012 at 17:35

Crankyadmin's user avatar

2

Python Image Library or PIL is an image processing module developed for Python. It provides image processing tools that help in creating, editing, and exporting image files. However, the PIL project was abandoned in 2011. To continue providing support for the latest Python versions, the Pillow module forked the PIL module. The Pillow module eventually replaced PIL and became the go-to image processing library for Python.

The Python interpreter may not detect specific modules when imported. Therefore, upon execution, Python will return the ModuleNotFoundError: No module named 'pil' exception and exits the program.

For example, let’s say we’re importing a package called “run”. We would do so by using the import statement followed by the package name; run. Since there is no module called “run”, this error is shown.

No module named "run"

Causes & Solutions For No Module Named Pil

There are multiple reasons why this exception may be raised. Let’s look at the following instances.

Package Not Installed Properly

This is probably the most typical reason for this exception. Some libraries may not be part of the Python Standard Library. Therefore they require additional installation steps before we can use them.

In specific IDEs (e.g., spyder), make sure your module are all installed in a single folder. PIP installer may install your package in one place, whereas the IDE expects the module in another directory. Make sure to save all external dependencies in one place.

It is vital to ensure that the correct installation commands for provided to install Pillow.

Windows Installation
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow

macOS Installation
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow

Linux Installation
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow

Multiple Python Versions Installed

Installing multiple versions of Python can result in multiple library folders for each version. Therefore, ensure the library is present in the correct version of Python.

Here’s how we can find the installation location for your version of Python

Open up the Python command terminal

Python application 3.10

Type the following lines of commands

import os
import sys
os.path.dirname(sys.executable)

Output

Python location

So the location would be: ‘C:UsersAdminAppDataLocalProgramsPythonPython310’

Incorrect Package Name

Certain packages have import statements that are different from their actual names. One notable example is a web scraping library called BeautifulSoup. The common user may attempt to import the module by calling import BeautifulSoup.

However, this is incorrect. You must go through the documents of each module and figure out the correct import command to avoid confusion. Furthermore, the correct implementation for the said example would be: import bs4

Importing Files

Another reason for the error to arise is importing Python files incorrectly. For example, let’s assume we’re importing the file “program.py”. To import this, we run “import program” excluding the .py extension. It is also essential to ensure that the file is present in the working directory. If failed to do so, the following error will appear:

No module named program

Another rule to remember is that do not use names of pre-existing packages as your Python file name i.e pil.py. If done otherwise, the Python interpreter will consider pandas as your Python file rather than the pil package itself. This will cause problems when working with your file and the package.

[Fixed] Module Seaborn has no Attribute Histplot Error

Python No Module Named Pil Visual Studio Code

Users tend to face an issue with the module in VSCode. Upon importing, the program may run perfectly, but under the problems tab, this may appear:

import PIL could not be resolved from source. Pylance(reportmissingmodulesource) 

This error is caused due to the fact that VS Code isn’t running the same Python interpreter between the two or more versions. Modules are installed on one of the Python versions you have. Therefore, we must determine the path to the Python executable. Refer to the following command

import sys
print(sys.executable)

This will show us the location in which Python is installed. If you run the same command on VS Code, it will show a different location. In order to have the versions in the same location, we must install the Python interpreter that is being used by VS Code. Type this in your terminal

/path/to/python/used/by/vs/code/python -m pip install pillow

No Module Named pil.imagetk

For Versions Below Python 3

This is due to the fact that Python is installed in a different location than the standard one. This can be fixed by re-installing Python to the standard location or by appending the location to sys.path.

For Versions Above Python 3

Python 3 and above imagetk comes under the Pillow module. Therefore, in order to import, run the following command.

PIL is a deprecated project, and no further support is provided. However, the Pillow project forked PIL to provide support for the latest Python versions. For macOS machines, the following command needs to be entered.

sudo pip install pillow

In some instances, the following error may appear.

ImportError: No module named PIL

An easy solution to this problem is to make sure PIP is upgraded to the latest versions. PIP makes sure all your packages are unzipped and loaded into Python, ready to use. Therefore, it is vital to upgrade PIP in order to install the latest versions of modules. You can upgrade PIP using the following command in macOS

sudo pip install  --upgrade pip

No Module Named PIL (Ubuntu)

In some versions of PIL in Ubuntu, it may come under the name imaging. Therefore in order to install Pillow in Ubuntu, run the following command.

sudo apt-get install python-imaging

No Module Named PIL (Raspberry Pi)

Upon installing the module on your Pi 0, you may be presented with the following error

sudo apt-get install python-pillow python-pil
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'python-pil' instead of 'python-pillow'
python-pil is already the newest version (5.4.1-2+deb10u2).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

Despite the successful installation, you may be presented with No Module Named Pil error upon running your Python file.

This may be due to the fact that the version of PIL and Python do not match. Make sure your Pi has the correct version of Python installed, and it makes sure the PIL installation matches your Python version.

Upon installation, the .exiftags function may not work. This may be due to the fact that other versions of the same module may cause the file to be deleted or overwritten.

Deleting all module versions and only saving the latest one can fix this issue.

FAQs

The module name is Pillow, but we use pil to import it. Why?

Support for Python Image Library has been discontinued. Therefore, for the module to work on newer Python versions, the Pillow project forked the existing PIL project. All functionalities from PIL are present in Pillow as well.

How to add pillow in requirements.txt?

Add RUN apk add zlib-dev jpeg-dev gcc musl-dev within your docker file and add Pillow within the requirements.txt file

What is the use of the Pillow module in Python?

Pillow provides image processing capabilities for Python. It has multiple file format support and powerful image processing abilities.

Conclusion

We’ve gone through various causes for Python No Module Named Pil exception. Make sure to keep these reasons in mind, as most “No Module Named” errors have similar reasons.

Trending Python Articles

  • [Fixed] Module Seaborn has no Attribute Histplot Error

    [Fixed] Module Seaborn has no Attribute Histplot Error

    January 18, 2023

  • Thonny: Text Wrapping Made Easy

    Thonny: Text Wrapping Made Easy

    by Rahul Kumar YadavJanuary 18, 2023

  • [Fixed] JavaScript error: IPython is Not Defined

    [Fixed] JavaScript error: IPython is Not Defined

    by Rahul Kumar YadavJanuary 18, 2023

  • [Fixed] “io.unsupportedoperation not readable” Error

    [Fixed] “io.unsupportedoperation not readable” Error

    by Rahul Kumar YadavJanuary 18, 2023

Thankfully, it’s now working. What I did was, I deleted pip from the location where it was saved, which in my case was:
C:UsersAppDataLocalMicrosoftWindowsApps. Then I installed it again using this website: https://datatofish.com/upgrade-pip/
This time, I installed it in (I changed the location with the help of that website):
C:UsersAppDataLocalProgramsPythonPython38-32Scripts
Then I used pip install pillow and installed it in the same place, Python Scripts area given above. Uninstall it using pip uninstall pillow if it wasn’t already.
Then import PIL in Python and it’ll work!

Could you please write down your approach step by step?

I’d like to try this suggestion but I am not sure if I can follow the directions correctly now.

Sure.

When I installed pillow from command prompt, I just entered the command pip install pillow and not specified any location, so it installed pillow to the default location, which in my case was C:Users<User Name>AppDataLocalMicrosoftWindowsApps (I’m pretty sure it’s the same in yours too).

So I went there (C:Users<User Name>AppDataLocalMicrosoftWindowsApps) and manually deleted pip from there the usual way like we delete files. Then, I installed pip using this website: https://datatofish.com/upgrade-pip/ to this location: C:Users<User name>AppDataLocalProgramsPythonPython38-32Scripts.

After I installed pip, using the same cd and cd (Given in the site), I changed the location to C:Users<User name>AppDataLocalProgramsPythonPython38-32Scripts and wrote pip install pillow. In the previous answer, I’ve written use pip uninstall pillow if it is already installed, but I guess it’ll uninstall itself if the whole pip is deleted. Still, to be on the safer side, you can use pip uninstall pillow first before installing.

Try importing PIL again in Python, and it should work!

Hope it helps ☺

  • #1

Здравствуйте! Сегодня столкнулся с проблемой — выбрасывает ошибку

Traceback (most recent call last):
File «C:UserskirilAppDataRoamingMicrosoftWindowsStart MenuProgramsPython 3.7питонецтестытест.py», line 1, in <module>
from PIL import Image, ImageFilter
ModuleNotFoundError: No module named ‘PIL’

Пытался удалять, скачивать pillow… Прочитал множество статей и вопросов на форумах, убив кучу времени. В итоге — не нашел ничего конкретно то, что мне нужно. Поэтому обращаюсь к вам.

Код:

Python:

from PIL import Image

img = Image.open('backgraund.png')
watermark = Image.open('text.png')

img.paste(watermark, (250, 250),  watermark)
img.save("img_with_watermark.png")

  • #2

А вы случайно не через PyCharm открываете?

  • #3

А вы случайно не через PyCharm открываете?

Нет

  • #4

ModuleNotFoundError: No module named ‘PIL’

В ошибке написано что модуль не установлен.
Возможно вы запускаете скрипт в виртуальном окружении, в котором не установлен модуль pillow (можно проверить с помощью команды pip list) или у вас установлено несколько версий питона и для той версии с помощью которой вы запускаете скрипт модуль pillow не установлен.

  • #5

В ошибке написано что модуль не установлен.
Возможно вы запускаете скрипт в виртуальном окружении, в котором не установлен модуль pillow (можно проверить с помощью команды pip list) или у вас установлено несколько версий питона и для той версии с помощью которой вы запускаете скрипт модуль pillow не установлен.

У меня установлено только питон 3.7, через pip list проверял и не однократно

  • #6

Может проблемы с путями.
Выполните в консоли команды pip -V (покажет версию pip, путь к папке с модулями и версию питона), а потом python -V чтобы убедиться что pip устанавливает пакеты для правильной версии питона.
Также можно выполнить скрипт:

Python:

import sys

print(sys.executable)

он покажет путь к файлу интерпретатора, сравните его с путем из команды pip -V.
Проверьте пути в PATH.

  • #7

Может проблемы с путями.
Выполните в консоли команды pip -V (покажет версию pip, путь к папке с модулями и версию питона), а потом python -V чтобы убедиться что pip устанавливает пакеты для правильной версии питона.
Также можно выполнить скрипт:

Python:

import sys

print(sys.executable)

он покажет путь к файлу интерпретатора, сравните его с путем из команды pip -V.
Проверьте пути в PATH.

Проверил, все сходится. Но все по прежнему так и не работает…

  • #8

Еще можно выполнить такой скрипт и проверить правильный ли там путь к установленным пакета (...libsite-packages):

Python:

import sys

print(sys.path)  # покажет все пути питона в PATH

Modulenotfounderror: no module named pil error occurs  if the pillow package is not installed or not properly configured. The best way to resolve this error is to reinstall the pillow module again. In some of the cases, the same error occurs because of importing the PIL module in the place of the image module.  In this article, we will see the different easiest ways to install pillow modules. Also, we will address the import issue. So let’s start.

The best and easiest way to install any python package is using any package manager either pip, conda, or some other like  easy_install. Here in a single line command we can install any python package.

pillow package

pillow package

Solution 1: pip for pillow installation –

Use this command to install the pillow with the pip package manager.

pip install Pillow

We can install any version of the pillow by just adding the version in the pillow command. For version, detail refers to the release details of pillow.

pip install Pillow==9.2.0

For admin rights please add sudo keyword in Linux similar OS and In windows, launch the cmd in Admin mode. If you are getting permission issues.
If pip is not properly configured then run the below command.

python -m pip install Pillow

Solution 2: conda for pillow installation –

conda comes with Anaconda distribution.

conda install -c conda-forge pillow

Here we can change the mirrors just like in the above command we are using conda-forge mirror we can use the below mirror as well.

conda pillow installation modulenotfounderror

conda pillow installation modulenotfounderror

Solution 3: Source for pillow installation –

Here we will build pillow packages locally. For this, we need to download the source code for the pillow package and then run the

python install setup.py

Notes :

We need to take care of few import statements like –

1. In the place of

import Image

use

from PIL import Image

2. In the place of

import _imaging

use

from PIL.Image import core as _imaging

Similar to Modulenotfounderror if you are experiencing importerror with PIL Read the below article.

Importerror no module named PIL Error Fix : In Steps

Other Must Read –

Importerror: cannot import name ‘pillow_version’ from ‘pil’ ( Solved )

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

If you use the Python image library and import PIL, you might get ImportError: No module named PIL while running the project. It happens due to the depreciation of the PIL library. Instead, it would help if you install and use its successor pillow library to resolve the issue.

If you use Python version 3 and try to install and use the PIL library, you will get the ImportError: No module named PIL while importing it, as shown below.

PIL is the Python Imaging Library developed by Fredrik Lundh and Contributors. Currently, PIL is depreciated, and Pillow is the friendly PIL fork by Alex Clark and Contributors. As of 2019, Pillow development is supported by Tidelift.

How to fix ImportError: No module named PIL?

If you are using Python version 3, the best way to resolve this is by uninstalling the existing PIL package and performing a clean installation of the Pillow package, as shown below.

Step 1: Uninstall the PIL package.

pip uninstall PIL

Step 2: Install the Pillow using pip as shown below on different operating systems.

On Windows

python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow

On Linux

easy_install Pillow 

On OSX  

brew install Pillow 

Note: Sometimes, while importing matplotlib in your Jupyter notebook, you might face this issue and doing a standard install of Pillow may not work out. You could do a force install of Pillow, as shown below, to resolve the error.

pip install --upgrade --force-reinstall Pillow
pip install --upgrade --force-reinstall matplotlib

Step 3: The most crucial class in the Python Imaging Library is the Image class, and you can import this as shown below.

from PIL import Image
im = Image.open("myimage.jpg")

If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:

print(im.format, im.size, im.mode)

#Output: PPM (512, 512) RGB

Note: If you use Python version 2.7, you need to install image and Pillow packages to resolve the issue.

python -m pip install image 
python -m pip install Pillow

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.



Я использую эту команду в оболочке для установки PIL:

easy_install PIL

затем я бегу python и введите этот: import PIL. Но я получаю эту ошибку:

Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named PIL

у меня никогда не было такой проблемы, как вы думаете?


1911  


16  

16 ответов:

на некоторых установках PIL, вы должны сделать

import Image

вместо import PIL (PIL на самом деле не всегда импортируется таким образом). Так как import Image работает для вас, это означает, что вы на самом деле установили PIL.

наличие другого имени для библиотеки и модуля Python необычно, но это то, что было выбрано для (некоторых версий) PIL.

вы можете получить дополнительную информацию о том, как использовать этот модуль из официальный учебник.

PS: на самом деле, на некоторые установка import PILтут работа, которая добавляет путаницы. Это подтверждается пример из документации, как выяснил @JanneKarila, а также некоторые более поздние версии пакета MacPorts PIL (1.1.7).

в консоли выполните:

pip install Pillow

внимание: PIL является устаревшим, и подушка является правопреемником.

на другой ноте, я могу настоятельно рекомендовать использование подушка который обратно совместим с PIL и лучше поддерживается/будет работать на более новых системах.

когда это установлено, вы можете сделать

import PIL 

или

from PIL import Image

etc..

это сработало для меня на Ubuntu 16.04:

sudo apt-get install python-imaging

на Wikibooks после поиска в течение примерно получаса.

иногда я получаю этот тип ошибки при запуске Unitest в python. Решение заключается в удалении и установке одного и того же пакета в виртуальной среде.

С помощью этой команды:

pip uninstall PIL

и

pip install  PIL 

Если по какой-либо причине вы получаете сообщение об ошибке, добавьте sudo в начале команды и после нажатия enter введите свой пароль.

в windows попробуйте проверить путь к местоположению библиотеки PIL. В моей системе я заметил, что путь был

Python26Libsite-packagespil instead of Python26Libsite-packagesPIL  

после переименования до PIL, Я был в состоянии загрузить в пильном модуле.

вместо пил использовать подушка он работает

easy_install Pillow

или

pip install Pillow

вам нужно будет установить образ и подушку с вашим пакетом python.
Будьте уверены, командная строка позаботится обо всем за вас.

нажмите

python-m pip install image

вы должны установить образ и подушку с вашим пакетом python.

тип

python -m pip install image 

или запустите командную строку (в windows), затем перейдите в папку scripts

cd C:Python27Scripts

затем выполните команду ниже

pip install image

Если вы используете anaconda:

conda install pillow

У меня была такая же проблема при импорте PIL и дальнейшем импорте модулей ImageTk и Image. Я также попытался установить PIL непосредственно через pip. но успеха добиться не удалось. Поскольку между ними было предложено, чтобы PIL был устаревшим, таким образом, попытался установить подушку только через pip. подушка была успешно установлена, далее, пакет PIL был сделан по пути: python27/Lib/site-packages/.

теперь можно импортировать как изображение, так и ImageTk.

Я недавно установил Leap. Я попробовал openshot, и он не начался. Поэтому пришел сюда и нашел предложение начать с терминала, чтобы увидеть, есть ли какие-либо ошибки.

ошибка у меня была error missing mlt. Поэтому я установил python-mlt модуль из Yast и импортировал его, попытался запустить, но следующий openshot сказал missing pil.

Я последовал предложению подушки для установки, потому что яст не мог найти никакого pil и импортировал pil. Это пошло нормально, но не началось и показало Error missing goocanvas.

Я установил goocanvas С Yast, импортировал его в python, и Openshot загорелся !!

С большим количеством ошибок в терминале, как missing Vimeoclient и серии attributeerrors. Ну, посмотрим, будет ли это какое-то влияние работать с ним.

я использовал conda-forge для установки подушки версии 5, и это, казалось, работало для меня:

conda install --channel conda-forge pillow=5

нормальная подушка установки conda не работала для меня.

вы, вероятно, не хватает заголовков python для построения pil. Если вы используете ubuntu или подобные, это будет что-то вроде

apt-get install python-dev

Понравилась статья? Поделить с друзьями:
  • Modern setup host ошибка обновления windows
  • Modern setup host windows 10 грузит процессор
  • Modern mobile mouse драйвер windows 7
  • Modern flyouts windows 10 скачать торрент
  • Modulenotfounderror no module named fcntl windows