Python Library for Computer Vision, OpenCV
OpenCV (Open Source Computer Vision Library) is one of the most widely-used open-source libraries for computer vision.
It offers various functionalities, including image processing, feature extraction, video transformation, and machine learning.
Installing OpenCV
OpenCV can be installed with the following command:
pip install opencv-python
It's important to note that to use OpenCV in Python code, you need to import the cv2
package.
import cv2
Why is OpenCV widely used?
OpenCV is one of the most popular libraries in the field of computer vision.
Its key advantages include:
-
Offers image and video processing functions (filtering, transformation, feature extraction, etc.)
-
Supports various formats (JPG, PNG, BMP, TIFF, etc.)
-
Provides hardware acceleration features (supports GPU)
-
Supports multiple languages like C++, Python, Java
-
Can be integrated with machine learning and deep learning (usable with TensorFlow, PyTorch, etc.)
Basic Usage of OpenCV
Let's explore the basic ways to process images and videos using the OpenCV library.
1. Loading an Image
To load an image, use the cv2.imread()
method.
import cv2 # Load the image image = cv2.imread("sample.jpg") # Display the image in a window cv2.imshow("Sample Image", image) cv2.waitKey(0) cv2.destroyAllWindows()
Use cv2.imread()
to load an image, and cv2.imshow()
to display it on the screen.
2. Resizing an Image
To adjust the size of an image, use the cv2.resize()
method.
resized_image = cv2.resize(image, (300, 300)) cv2.imshow("Resized Image", resized_image) cv2.waitKey(0) cv2.destroyAllWindows()
The code above resizes the image to 300x300
and displays it.
3. Converting to Grayscale
Here's how to convert an image to grayscale.
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("Grayscale Image", gray_image) cv2.waitKey(0) cv2.destroyAllWindows()
You can now convert a color image to a grayscale image.
Using OpenCV makes implementing image processing and computer vision tasks straightforward.
In the next lessons, we'll cover advanced features like edge detection and object detection.
Which of the following is the correct code to import OpenCV?
import cv2
import opencv
import openCV2
import cv
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help