AI with Python – Computer Vision, Some Basic Functions in openCV for images how to install opencv

3 min read 6 hours ago
Published on Feb 11, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial guides you through the basics of using OpenCV with Python for computer vision tasks. OpenCV (Open Source Computer Vision) is a powerful library that allows you to perform real-time image processing. This step-by-step guide will help you install OpenCV, load and display images, and perform basic operations like rotating images.

Step 1: Install OpenCV

Before you can use OpenCV, you need to install it. Follow these steps for a successful installation.

  1. Open Command Prompt or Terminal.

  2. Ensure Python is Installed: Check if Python is installed by running:

    python --version
    

    If Python is not installed, download it from the official Python website.

  3. Install OpenCV: Use pip to install OpenCV with the following command:

    pip install opencv-python
    
  4. Verify Installation: After installation, verify it by running the following command in Python:

    import cv2
    print(cv2.__version__)
    

    This should display the version of OpenCV installed.

Step 2: Load an Image

Once OpenCV is installed, you can load an image to start processing.

  1. Import OpenCV:

    import cv2
    
  2. Load the Image: Use the imread function to load an image file:

    image = cv2.imread('path/to/your/image.jpg')
    
  3. Check if the Image Loaded Successfully:

    if image is None:
        print("Error: Image not found")
    

Step 3: Display an Image

After loading an image, you can display it in a window.

  1. Use the imshow Function:

    cv2.imshow('Loaded Image', image)
    
  2. Wait for a Key Press:

    cv2.waitKey(0)  # Wait indefinitely until a key is pressed
    
  3. Close the Image Window:

    cv2.destroyAllWindows()
    

Step 4: Rotate an Image

You can easily rotate an image using OpenCV.

  1. Define the Rotation Function:

    def rotate_image(image, angle):
        h, w = image.shape[:2]
        center = (w // 2, h // 2)
        matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
        rotated = cv2.warpAffine(image, matrix, (w, h))
        return rotated
    
  2. Rotate the Image: Call the function with your desired angle:

    rotated_image = rotate_image(image, 45)  # Rotate 45 degrees
    
  3. Display the Rotated Image:

    cv2.imshow('Rotated Image', rotated_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

Conclusion

In this tutorial, you learned how to install OpenCV, load and display images, and perform basic image manipulation like rotation. OpenCV is a versatile library that opens the door to various computer vision applications. As next steps, consider exploring more advanced features of OpenCV, such as image filtering, edge detection, and object recognition to expand your skills in computer vision.