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.
What is ImportError: No module named PIL?
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.
python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow
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
Thanks for this! 😀