0
0
PythonHow-ToBeginner · 3 min read

How to Open Image in Python: Simple Guide with Examples

To open an image in Python, use the Pillow library's Image.open() function by passing the image file path as a string. This loads the image so you can view or manipulate it in your program.
📐

Syntax

The basic syntax to open an image using Pillow is:

  • Image.open(path): Opens the image file located at path.
  • path: A string representing the file path to the image.
  • The function returns an Image object that you can use to display or edit the image.
python
from PIL import Image

img = Image.open('path/to/image.jpg')
💻

Example

This example shows how to open an image file and display it using Pillow.

python
from PIL import Image

# Open an image file
img = Image.open('example.jpg')

# Display the image
img.show()
Output
A window opens showing the image 'example.jpg'.
⚠️

Common Pitfalls

Common mistakes when opening images in Python include:

  • Not installing the Pillow library before importing PIL.
  • Using an incorrect or relative file path that does not point to the image.
  • Trying to open unsupported file formats.

Always ensure the image file exists at the specified path and Pillow is installed with pip install Pillow.

python
from PIL import Image

# Wrong: File path typo
# img = Image.open('exmple.jpg')  # This will cause FileNotFoundError

# Right: Correct file path
img = Image.open('example.jpg')
📊

Quick Reference

Summary tips for opening images in Python:

  • Install Pillow with pip install Pillow.
  • Use Image.open('file_path') to load images.
  • Call img.show() to display the image.
  • Check file paths carefully to avoid errors.

Key Takeaways

Use Pillow's Image.open() to open image files in Python.
Always install Pillow before importing it.
Provide the correct file path to avoid errors.
Use img.show() to display the opened image.
Supported formats include JPEG, PNG, BMP, and more.