Reading images using Python?

Reading images is a fundamental task in computer vision and image processing. Python offers several powerful libraries for this purpose, with OpenCV and PIL (Pillow) being the most popular choices. This tutorial covers both approaches for reading, displaying, and saving images.

Installing Required Libraries

First, install the necessary packages using pip ?

$ pip install opencv-python
$ pip install numpy
$ pip install Pillow

Reading Images Using OpenCV

OpenCV (Open Source Computer Vision) is a comprehensive library for computer vision tasks. It provides over 2,500 optimized algorithms for image processing, machine learning, and computer vision applications.

Basic Image Reading

Use cv2.imread() to read an image. The image should be in your current working directory or provide the absolute path ?

import numpy as np
import cv2

# Read image in grayscale
img = cv2.imread('bike.jpg', 0)

# Read image in color (default)
img_color = cv2.imread('bike.jpg', 1)

The second parameter controls the reading mode:

  • 0 or cv2.IMREAD_GRAYSCALE ? Load as grayscale
  • 1 or cv2.IMREAD_COLOR ? Load as color (default)
  • -1 or cv2.IMREAD_UNCHANGED ? Load with alpha channel

Displaying Images

Use cv2.imshow() to display images in a window ?

import cv2

img = cv2.imread('bike.jpg', 0)

# Display the image
cv2.imshow('Image Window', img)

# Wait for key press
cv2.waitKey(0)

# Close all windows
cv2.destroyAllWindows()

Saving Images

Use cv2.imwrite() to save images. The first argument is the filename, the second is the image data ?

# Save the processed image
cv2.imwrite('processed_bike.jpg', img)

Complete OpenCV Example

import numpy as np
import cv2

# Read the image
img = cv2.imread('bike.jpg', 0)

# Display the image
cv2.imshow('Original Image', img)

# Wait for key press
k = cv2.waitKey(0)

# Press 's' to save, ESC to exit
if k == 27:  # ESC key
    cv2.destroyAllWindows()
elif k == ord('s'):  # 's' key
    cv2.imwrite('saved_bike.jpg', img)
    cv2.destroyAllWindows()

Reading Images Using PIL (Pillow)

PIL (Python Imaging Library), now known as Pillow, is another excellent library for image manipulation. It's particularly useful for basic image operations and format conversions.

Basic PIL Operations

from PIL import Image, ImageFilter

# Read image
img = Image.open('sample.jpg')

# Display basic information
print(f"Format: {img.format}")
print(f"Size: {img.size}")
print(f"Mode: {img.mode}")
Format: JPEG
Size: (800, 600)
Mode: RGB

Image Processing with PIL

from PIL import Image, ImageFilter

# Read image
img = Image.open('bike.jpg')

# Apply a filter
sharpened = img.filter(ImageFilter.SHARPEN)

# Save the processed image
sharpened.save('sharpened_bike.jpg', 'JPEG')

# Convert to grayscale
grayscale = img.convert('L')
grayscale.save('grayscale_bike.jpg')

Comparison of Libraries

Feature OpenCV PIL/Pillow
Performance High (C++ backend) Moderate
Computer Vision Extensive algorithms Basic operations
File Format Support Good Excellent
Ease of Use Moderate Simple
Best For Computer vision tasks Basic image processing

Error Handling

Always check if images are loaded successfully to avoid runtime errors ?

import cv2

# OpenCV error handling
img = cv2.imread('nonexistent.jpg')
if img is None:
    print("Error: Could not load image")
else:
    print("Image loaded successfully")

# PIL error handling
try:
    from PIL import Image
    img = Image.open('nonexistent.jpg')
    print("Image loaded successfully")
except FileNotFoundError:
    print("Error: File not found")
Error: Could not load image
Error: File not found

Conclusion

OpenCV is ideal for computer vision applications requiring advanced image processing, while PIL/Pillow excels at basic image manipulation and format conversion. Choose OpenCV for performance-critical applications and PIL for simple image tasks. Both libraries are essential tools in the Python image processing ecosystem.

Updated on: 2026-03-25T05:28:15+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements