Image processing in Python?

Python provides powerful libraries for image processing, including OpenCV for computer vision, PIL/Pillow for basic operations, and NumPy/SciPy for numerical image manipulation. This tutorial covers essential image processing techniques using these libraries.

Popular Image Processing Libraries

  • OpenCV − Computer vision library for real-time processing, facial recognition, object detection, and advanced image analysis.

  • PIL/Pillow − User-friendly library for basic operations like resize, rotate, format conversion, and thumbnail creation.

  • NumPy and SciPy − Mathematical libraries for advanced image manipulation and numerical processing.

  • Matplotlib − Plotting library useful for displaying images and creating visualizations.

Installing Required Libraries

Install the necessary libraries using pip ?

pip install pillow opencv-python matplotlib numpy

Basic Image Operations with PIL

Opening and Displaying Images

Load an image file and perform basic operations ?

from PIL import Image
import matplotlib.pyplot as plt

# Create a simple colored image for demonstration
img = Image.new('RGB', (200, 200), color='lightblue')
img.show()

# Get image information
print(f"Size: {img.size}")
print(f"Mode: {img.mode}")
Size: (200, 200)
Mode: RGB

Image Rotation

Rotate images by specified angles ?

from PIL import Image

# Create a simple image with pattern
img = Image.new('RGB', (100, 100), color='red')
# Add a blue rectangle
for i in range(20, 80):
    for j in range(20, 80):
        img.putpixel((i, j), (0, 0, 255))

# Rotate the image
rotated = img.rotate(45)
print("Image rotated by 45 degrees")
Image rotated by 45 degrees

Format Conversion and Saving

Convert between different image formats ?

from PIL import Image

# Create a sample image
img = Image.new('RGB', (100, 100), color='green')

# Save in different formats (in-memory demonstration)
print("Original format: RGB")
print(f"Image size: {img.size}")

# Convert to grayscale
gray_img = img.convert('L')
print(f"Converted to grayscale mode: {gray_img.mode}")
Original format: RGB
Image size: (100, 100)
Converted to grayscale mode: L

Creating Thumbnails

Resize images while maintaining aspect ratio ?

from PIL import Image

# Create a larger image
img = Image.new('RGB', (400, 300), color='purple')
print(f"Original size: {img.size}")

# Create thumbnail
img.thumbnail((100, 100))
print(f"Thumbnail size: {img.size}")
Original size: (400, 300)
Thumbnail size: (100, 75)

Grayscale Conversion

Convert color images to grayscale using the 'L' mode ?

from PIL import Image
import numpy as np

# Create a colorful image
img = Image.new('RGB', (100, 100))
pixels = []
for y in range(100):
    for x in range(100):
        pixels.append((x*2, y*2, 128))
img.putdata(pixels)

# Convert to grayscale
gray_img = img.convert('L')
print(f"Original mode: {img.mode}")
print(f"Grayscale mode: {gray_img.mode}")
print("Conversion completed successfully")
Original mode: RGB
Grayscale mode: L
Conversion completed successfully

Advanced Processing with OpenCV

OpenCV provides more advanced image processing capabilities ?

import cv2
import numpy as np

# Create a sample image using NumPy
img_array = np.zeros((200, 200, 3), dtype=np.uint8)
img_array[50:150, 50:150] = [255, 0, 0]  # Red square

# Convert to grayscale using OpenCV
gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)

print(f"Original shape: {img_array.shape}")
print(f"Grayscale shape: {gray.shape}")
print("OpenCV conversion completed")
Original shape: (200, 200, 3)
Grayscale shape: (200, 200)
OpenCV conversion completed

Displaying Images with Matplotlib

Use Matplotlib for better image display and analysis ?

import matplotlib.pyplot as plt
import numpy as np

# Create a sample image
img = np.random.rand(50, 50, 3)  # Random colored image

# Display using matplotlib
plt.figure(figsize=(6, 3))

plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title('Original')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(img, cmap='gray')
plt.title('Grayscale Display')
plt.axis('off')

plt.tight_layout()
plt.show()
print("Images displayed successfully")
Images displayed successfully

Common Image Operations Summary

Operation PIL/Pillow OpenCV Best For
Basic Operations ? ? Simple tasks
Format Conversion ? ? File handling
Computer Vision ? ? Advanced analysis
Easy Syntax ? ? Beginners

Conclusion

Python offers excellent image processing capabilities through PIL/Pillow for basic operations and OpenCV for advanced computer vision tasks. Choose PIL for simple image manipulation and OpenCV for complex analysis and real-time processing applications.

Updated on: 2026-03-25T05:33:13+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements