AI with Python – Computer Vision, Some Basic Functions in openCV for images how to install opencv
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.
-
Open Command Prompt or Terminal.
-
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.
-
Install OpenCV: Use pip to install OpenCV with the following command:
pip install opencv-python
-
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.
-
Import OpenCV:
import cv2
-
Load the Image: Use the
imread
function to load an image file:image = cv2.imread('path/to/your/image.jpg')
-
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.
-
Use the
imshow
Function:cv2.imshow('Loaded Image', image)
-
Wait for a Key Press:
cv2.waitKey(0) # Wait indefinitely until a key is pressed
-
Close the Image Window:
cv2.destroyAllWindows()
Step 4: Rotate an Image
You can easily rotate an image using OpenCV.
-
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
-
Rotate the Image: Call the function with your desired angle:
rotated_image = rotate_image(image, 45) # Rotate 45 degrees
-
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.