Skip to content

Advanced Image Processing with OpenCV

Abstract

Advanced Image Processing with OpenCV is a Python application that demonstrates a variety of image processing techniques using the OpenCV library. The project covers filtering, edge detection, feature extraction, and image transformations, providing a modular and extensible framework for computer vision tasks.

Prerequisites

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of image processing
  • Required libraries: opencv-pythonopencv-python, numpynumpy, matplotlibmatplotlib

Before you Start

Install Python and the required libraries:

Install dependencies
pip install opencv-python numpy matplotlib
Install dependencies
pip install opencv-python numpy matplotlib

Getting Started

Create a Project

  1. Create a folder named advanced-image-processing-opencvadvanced-image-processing-opencv.
  2. Open the folder in your code editor or IDE.
  3. Create a file named advanced_image_processing_with_opencv.pyadvanced_image_processing_with_opencv.py.
  4. Copy the code below into your file.

Write the Code

⚙️ Advanced Image Processing with OpenCV
Advanced Image Processing with OpenCV
"""
Advanced Image Processing with OpenCV
 
This project demonstrates advanced image processing techniques using OpenCV, including edge detection, filtering, morphological operations, color transformations, and saving processed images. Includes CLI for selecting processing type.
"""
import cv2
import numpy as np
import argparse
import os
 
def process_image(image_path, mode, out_path=None):
    img = cv2.imread(image_path)
    if img is None:
        print(f"Error: Could not load image {image_path}")
        return
    if mode == 'gray':
        result = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    elif mode == 'edges':
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        result = cv2.Canny(gray, 100, 200)
    elif mode == 'blur':
        result = cv2.GaussianBlur(img, (5,5), 0)
    elif mode == 'morph':
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        result = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, np.ones((5,5), np.uint8))
    elif mode == 'hsv':
        result = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    else:
        print(f"Unknown mode: {mode}")
        return
    cv2.imshow(f'{mode.capitalize()} Image', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    if out_path:
        if len(result.shape) == 2:
            cv2.imwrite(out_path, result)
        else:
            cv2.imwrite(out_path, cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
        print(f"Saved processed image to {out_path}")
 
def main():
    parser = argparse.ArgumentParser(description="Advanced Image Processing with OpenCV")
    parser.add_argument('--image', type=str, required=True, help='Path to image file')
    parser.add_argument('--mode', type=str, choices=['gray', 'edges', 'blur', 'morph', 'hsv'], required=True, help='Processing mode')
    parser.add_argument('--out', type=str, help='Output file path')
    args = parser.parse_args()
    process_image(args.image, args.mode, args.out)
 
if __name__ == "__main__":
    main()
 
Advanced Image Processing with OpenCV
"""
Advanced Image Processing with OpenCV
 
This project demonstrates advanced image processing techniques using OpenCV, including edge detection, filtering, morphological operations, color transformations, and saving processed images. Includes CLI for selecting processing type.
"""
import cv2
import numpy as np
import argparse
import os
 
def process_image(image_path, mode, out_path=None):
    img = cv2.imread(image_path)
    if img is None:
        print(f"Error: Could not load image {image_path}")
        return
    if mode == 'gray':
        result = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    elif mode == 'edges':
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        result = cv2.Canny(gray, 100, 200)
    elif mode == 'blur':
        result = cv2.GaussianBlur(img, (5,5), 0)
    elif mode == 'morph':
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        result = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, np.ones((5,5), np.uint8))
    elif mode == 'hsv':
        result = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    else:
        print(f"Unknown mode: {mode}")
        return
    cv2.imshow(f'{mode.capitalize()} Image', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    if out_path:
        if len(result.shape) == 2:
            cv2.imwrite(out_path, result)
        else:
            cv2.imwrite(out_path, cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
        print(f"Saved processed image to {out_path}")
 
def main():
    parser = argparse.ArgumentParser(description="Advanced Image Processing with OpenCV")
    parser.add_argument('--image', type=str, required=True, help='Path to image file')
    parser.add_argument('--mode', type=str, choices=['gray', 'edges', 'blur', 'morph', 'hsv'], required=True, help='Processing mode')
    parser.add_argument('--out', type=str, help='Output file path')
    args = parser.parse_args()
    process_image(args.image, args.mode, args.out)
 
if __name__ == "__main__":
    main()
 

Example Usage

Run the image processor
python advanced_image_processing_with_opencv.py
Run the image processor
python advanced_image_processing_with_opencv.py

Explanation

Key Features

  • Filtering: Apply Gaussian, median, and bilateral filters.
  • Edge Detection: Use Canny, Sobel, and Laplacian methods.
  • Feature Extraction: Detect corners and keypoints.
  • Image Transformations: Resize, rotate, and crop images.
  • Error Handling: Validates inputs and manages exceptions.
  • CLI Interface: Interactive command-line usage.

Code Breakdown

  1. Import Libraries and Load Image
advanced_image_processing_with_opencv.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
advanced_image_processing_with_opencv.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Filtering Functions
advanced_image_processing_with_opencv.py
def apply_filters(img):
    gaussian = cv2.GaussianBlur(img, (5, 5), 0)
    median = cv2.medianBlur(img, 5)
    bilateral = cv2.bilateralFilter(img, 9, 75, 75)
    return gaussian, median, bilateral
advanced_image_processing_with_opencv.py
def apply_filters(img):
    gaussian = cv2.GaussianBlur(img, (5, 5), 0)
    median = cv2.medianBlur(img, 5)
    bilateral = cv2.bilateralFilter(img, 9, 75, 75)
    return gaussian, median, bilateral
  1. Edge Detection Methods
advanced_image_processing_with_opencv.py
def edge_detection(img):
    canny = cv2.Canny(img, 100, 200)
    sobel = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
    laplacian = cv2.Laplacian(img, cv2.CV_64F)
    return canny, sobel, laplacian
advanced_image_processing_with_opencv.py
def edge_detection(img):
    canny = cv2.Canny(img, 100, 200)
    sobel = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
    laplacian = cv2.Laplacian(img, cv2.CV_64F)
    return canny, sobel, laplacian
  1. Feature Extraction
advanced_image_processing_with_opencv.py
def feature_extraction(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
    return corners
advanced_image_processing_with_opencv.py
def feature_extraction(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
    return corners
  1. CLI Interface and Error Handling
advanced_image_processing_with_opencv.py
def main():
    print("Advanced Image Processing with OpenCV")
    img_path = input("Enter image path: ")
    try:
        img = cv2.imread(img_path)
        if img is None:
            raise ValueError("Image not found.")
        gaussian, median, bilateral = apply_filters(img)
        canny, sobel, laplacian = edge_detection(img)
        corners = feature_extraction(img)
        print(f"Corners detected: {len(corners) if corners is not None else 0}")
        # Display results (optional)
        # plt.imshow(canny, cmap='gray')
        # plt.show()
    except Exception as e:
        print(f"Error: {e}")
 
if __name__ == "__main__":
    main()
advanced_image_processing_with_opencv.py
def main():
    print("Advanced Image Processing with OpenCV")
    img_path = input("Enter image path: ")
    try:
        img = cv2.imread(img_path)
        if img is None:
            raise ValueError("Image not found.")
        gaussian, median, bilateral = apply_filters(img)
        canny, sobel, laplacian = edge_detection(img)
        corners = feature_extraction(img)
        print(f"Corners detected: {len(corners) if corners is not None else 0}")
        # Display results (optional)
        # plt.imshow(canny, cmap='gray')
        # plt.show()
    except Exception as e:
        print(f"Error: {e}")
 
if __name__ == "__main__":
    main()

Features

  • Comprehensive Image Processing: Filtering, edge detection, feature extraction
  • Modular Design: Separate functions for each task
  • Error Handling: Manages invalid inputs and exceptions
  • Production-Ready: Scalable and maintainable code

Next Steps

Enhance the project by:

  • Adding more filters and edge detectors
  • Supporting batch processing of images
  • Creating a GUI with Tkinter or a web app with Flask
  • Integrating with machine learning models for classification
  • Adding visualization of results
  • Unit testing for reliability

Educational Value

This project teaches:

  • Image Processing: Filtering, edge detection, feature extraction
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code

Real-World Applications

  • Medical Imaging
  • Security Systems
  • Photo Editing Tools
  • Industrial Automation

Conclusion

Advanced Image Processing with OpenCV provides a robust framework for performing a variety of image processing tasks. With modular design and extensibility, this project can be adapted for real-world computer vision applications. For more advanced projects, visit Python Central Hub.

Was this page helpful?

Let us know how we did