投稿日:2025年1月7日

How to use OpenCV with Python

Introduction to OpenCV and Python

OpenCV, or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library.
It is designed to process images and video to identify objects, faces, or even the handwriting of a human.
With libraries like OpenCV, programmers can create real-time applications for various complex visual tasks.

Python, being a user-friendly language with an easy-to-read syntax, has become one of the favorite programming languages to work with OpenCV.
Python’s extensive collection of libraries and its flexibility enhance OpenCV’s capabilities, enabling developers to create robust and efficient applications.

Setting Up OpenCV in Python

Step 1: Install Python

Before getting started with OpenCV, you need to ensure that Python is installed on your system.
You can download and install it from Python’s official website.
It’s advisable to download the latest version for optimal functionality and features.

Step 2: Install OpenCV Library

Once Python is installed, the next task is to install the OpenCV library.
This can be done easily with the package manager `pip`.
Open your command prompt or terminal and type the following command:

“`
pip install opencv-python
“`

If you need the additional functionality offered by OpenCV’s additional modules (like `cv2`), you’ll also need to install:

“`
pip install opencv-contrib-python
“`

Step 3: Verify the Installation

After the installation process, verify that OpenCV has been successfully installed by typing the subsequent command in the Python prompt:

“`python
import cv2
print(cv2.__version__)
“`

If no error is thrown and the version number is printed, your installation was successful.

Basic Operations with OpenCV

Reading and Displaying Images

One of the fundamental operations in OpenCV is reading an image and displaying it.
Here is a simple Python code snippet for this task:

“`python
import cv2

# Read image
image = cv2.imread(‘example.jpg’)

# Display image
cv2.imshow(‘Displayed Image’, image)

# Wait until a key is pressed
cv2.waitKey(0)

# Destroy all windows
cv2.destroyAllWindows()
“`

Converting Color Spaces

In computer vision, changing color spaces is quite common.
For instance, to convert an image from BGR (Blue, Green, Red) to Grayscale, you can use:
“`python
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
“`

Advanced Image Processing Techniques

Edge Detection

One of the exciting features of OpenCV is its ability to perform edge detection.
Here’s how you can achieve that using the Canny edge detection method:

“`python
edges = cv2.Canny(image, 100, 200)
cv2.imshow(‘Edges’, edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
“`

This code will reveal the edges present in an image which can be particularly useful in object detection.

Image Thresholding

Image thresholding is a technique for segmenting an image.
In OpenCV, you can do this by:

“`python
_, thresholded_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
cv2.imshow(‘Thresholded Image’, thresholded_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
“`

Here, the threshold value is set to 127.
Pixel values below this threshold are turned to black, while those above are turned to white.

Working with Videos

Capturing Video from a Camera

Apart from static image processing, OpenCV excels in video processing.
This includes capturing video from a connected camera:

“`python
cap = cv2.VideoCapture(0)

while True:
ret, frame = cap.read()
cv2.imshow(‘Video Frame’, frame)

if cv2.waitKey(1) & 0xFF == ord(‘q’):
break

cap.release()
cv2.destroyAllWindows()
“`

Pressing ‘q’ will quit the video capture loop and close the window.

Writing Video to a File

OpenCV can also write frames to a video file:

“`python
fourcc = cv2.VideoWriter_fourcc(*’XVID’)
out = cv2.VideoWriter(‘output.avi’, fourcc, 20.0, (640, 480))

while True:
ret, frame = cap.read()

if not ret:
break

out.write(frame)
cv2.imshow(‘Frame’, frame)

if cv2.waitKey(1) & 0xFF == ord(‘q’):
break

cap.release()
out.release()
cv2.destroyAllWindows()
“`

This snippet writes the video capture to ‘output.avi’ file in Xvid format.

Conclusion

OpenCV and Python together make a powerful duo for anyone interested in computer vision or image processing tasks.
By following the steps and code snippets above, even beginners can quickly start experimenting with basic and advanced image processing techniques.
As with any skill, practice and continual learning will unlock more complex and exciting projects.
So dive in, explore, and transform the way you interact with images and video using the power of OpenCV and Python.

You cannot copy content of this page