Introduction to C++ OpenCV Basic Modules
OpenCV is a powerful computer vision library containing multiple modules, each focused on different tasks.
Below are some core modules in OpenCV:
| Module name | Main Function | Common classes/functions |
|---|---|---|
| Core | Provides basic data structures and functions, such as image storage, matrix operations, file I/O, etc. | Mat, Point, Size, Rect, Scalar, FileStorage, cv::format |
| Imgproc | Image processing functions, including filtering, geometric transformations, color space conversion, edge detection, morphological operations, thresholding, etc. | cvtColor, GaussianBlur, Canny, threshold, resize, warpAffine |
| Highgui | Display of images and video, window management, and user interaction (such as mouse events, sliders). | imshow, namedWindow, waitKey, createTrackbar, setMouseCallback |
| Video | Video processing functions, including video capture, background subtraction, optical flow computation, etc. | VideoCapture, VideoWriter, BackgroundSubtractor, calcOpticalFlowPyrLK |
| Calib3d | Camera calibration, 3D reconstruction, pose estimation, etc. | findChessboardCorners, calibrateCamera, solvePnP, recoverPose |
| Features2d | Feature detection and description, including keypoint detection, feature matching, etc. | ORB, SIFT, SURF, BFMatcher, FlannBasedMatcher |
| Objdetect | Object detection functions, such as Haar cascade detection, HOG detection, etc. | CascadeClassifier, HOGDescriptor |
| DNN | Loading and inference of deep learning models, supporting frameworks such as TensorFlow, PyTorch, Caffe, etc. | readNet, blobFromImage, Net::forward |
| ML | Machine learning algorithms, such as KNN, SVM, decision trees, etc. | KNearest, SVM, DTrees, TrainData |
| Flann | Fast approximate nearest neighbor search (FLANN), used for feature matching and high-dimensional data search. | Index, KDTreeIndexParams, SearchParams |
| Photo | Image inpainting, denoising, HDR imaging, etc. | inpaint, fastNlMeansDenoising, createTonemap |
| Stitching | Image stitching functions, used to create panoramas. | Stitcher, Stitcher::create |
| Shape | Shape analysis and matching. | ShapeDistanceExtractor, ShapeContextDistanceExtractor |
| Tracking | Object tracking algorithms, such as MIL, KCF, GOTURN, etc. | TrackerMIL, TrackerKCF, TrackerGOTURN |
| Videoio | Video input/output functions, supporting multiple video formats and cameras. | VideoCapture, VideoWriter, CAP_PROP_FRAME_WIDTH, CAP_PROP_FRAME_HEIGHT |
| Imgcodecs | Reading and saving image files, supporting multiple image formats. | imread, imwrite, imdecode, imencode |
| Xfeatures2d | Additional feature detection and description algorithms such as SIFT, SURF, FREAK, etc. | SIFT, SURF, FREAK, DAISY |
| Superres | Super-resolution image processing. | SuperResolution, DenseOpticalFlowExt |
| Optflow | Optical flow computation and motion analysis. | calcOpticalFlowFarneback, calcOpticalFlowPyrLK |
| Cuda | GPU-accelerated computer vision algorithms. | cuda::GpuMat, cuda::Stream, cuda::resize |
| Contrib | Additional community-contributed features such as face recognition, text detection, etc. | FaceRecognizer, TextDetector |
1. Core module
core The Core module is OpenCV's core module, providing basic data structures and functions.
Main Function
-
Basic data structures:
-
Mat: used to store image and matrix data. -
Point、Size、Rect: used to represent points, sizes, and rectangular regions. -
Scalar: used to represent colors or pixel values.
Mat: used to store image and matrix data.
Point、Size、Rect: used to represent points, sizes, and rectangular regions.
Scalar: used to represent colors or pixel values.
-
Matrix operations:
-
Matrix creation, copying, conversion, arithmetic operations, etc.
Matrix creation, copying, conversion, arithmetic operations, etc.
-
File I/O:
-
Reading and saving images, videos, XML/YAML files, etc.
Reading and saving images, videos, XML/YAML files, etc.
-
Memory management:
-
Automatic memory management with reference counting.
Automatic memory management with reference counting.
Example
#include
#include
using
namespace
cv
;
using
namespace
std
;
int
main
(
)
{
// create a 3x3 matrix
Mat mat
=
(
Mat_
<
int
(
3
,
3
)
<<
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
);
// output the matrix
cout
<<
"Matrix:\n"
<<
mat
<<
endl
;
// access matrix elements
int
value
=
mat.
at
<
int
(
1
,
1
);
cout
<<
"Value at (1, 1): "
<<
value
<<
endl
;
return
0
;
}
2. Imgproc Module
imgproc The module provides image processing functions, including filtering, geometric transformations, color space conversion, etc.
Main Function
-
Image filtering:
-
Mean filtering, Gaussian filtering, median filtering, etc.
Mean filtering, Gaussian filtering, median filtering, etc.
-
Geometric transformation:
-
Scaling, rotation, affine transformations, perspective transformations, etc.
Scaling, rotation, affine transformations, perspective transformations, etc.
-
Color space conversion:
-
Conversion from RGB to grayscale, HSV, Lab, and other color spaces.
Conversion from RGB to grayscale, HSV, Lab, and other color spaces.
-
Edge detection:
-
Edge detection algorithms such as Canny, Sobel, and Laplacian.
Edge detection algorithms such as Canny, Sobel, and Laplacian.
-
Morphological operations:
-
Erosion, dilation, opening, closing, etc.
Erosion, dilation, opening, closing, etc.
-
Thresholding:
-
Simple thresholding, adaptive thresholding, etc.
Simple thresholding, adaptive thresholding, etc.
Example
#include
#include
using
namespace
cv
;
int
main
(
)
{
// Read image
Mat image
=
imread
(
"test.jpg"
)
;
if
(
image.
empty
(
)
)
return
1
;
// convert to grayscale image
Mat grayImage
;
cvtColor
(
image, grayImage, COLOR_BGR2GRAY
)
;
// Gaussian filtering
Mat blurredImage
;
GaussianBlur
(
grayImage, blurredImage, Size
(
5
,
5
)
,
0
)
;
// Display the result
imshow
(
"Original Image"
, image
)
;
imshow
(
"Blurred Image"
, blurredImage
)
;
waitKey
(
0
)
;
return
0
;
}
3. Highgui Module
highgui The module provides image and video display, window management, and user interaction functions.
Main Function
-
Image display:
-
Create windows, display images, wait for user input.
Create windows, display images, wait for user input.
-
Video capture:
-
Read frames from a camera or video file.
Read frames from a camera or video file.
-
User interaction:
-
Mouse events, sliders, buttons, etc.
Mouse events, sliders, buttons, etc.
Example
#include
using
namespace
cv
;
int
main
(
)
{
// Read image
Mat image
=
imread
(
"test.jpg"
)
;
if
(
image.
empty
(
)
)
return
1
;
// Create a window and display the image
namedWindow
(
"Display Window"
, WINDOW_AUTOSIZE
)
;
imshow
(
"Display Window"
, image
)
;
// wait for user keypress
waitKey
(
0
)
;
// close the window
destroyAllWindows
(
)
;
return
0
;
}
4. Video Module
video The module provides video processing functions, including video capture, background subtraction, optical flow computation, etc.
Main Function
-
Video capture:
-
Read frames from a camera or video file.
Read frames from a camera or video file.
-
Background subtraction:
-
Extract foreground objects from video.
Extract foreground objects from video.
-
Optical flow computation:
-
Compute the motion of objects in images.
Compute the motion of objects in images.
Example
#include
#include
using
namespace
cv
;
int
main
(
)
{
// open the camera
VideoCapture cap
(
0
)
;
if
(
!
cap.
isOpened
(
)
)
return
1
;
Mat frame
;
while
(
true
)
{
// read a frame
cap
frame
;
if
(
frame.
empty
(
)
)
break
;
// display the frame
imshow
(
"Camera Feed"
, frame
)
;
// press ESC to exit
if
(
waitKey
(
30
)
==
27
)
break
;
}
// release the camera and close the window
cap.
release
(
)
;
destroyAllWindows
(
)
;
return
0
;
}
5. Calib3d Module
calib3d The module provides camera calibration, 3D reconstruction, pose estimation, and other functions.
Main Function
-
Camera calibration:
-
Compute camera intrinsic parameters and distortion coefficients.
Compute camera intrinsic parameters and distortion coefficients.
-
3D reconstruction:
-
Reconstruct a 3D scene from multi-view images.
Reconstruct a 3D scene from multi-view images.
-
Pose estimation:
-
Estimate the 3D pose of objects.
Estimate the 3D pose of objects.
Example
#include
#include
using
namespace
cv
;
int
main
(
)
{
// Read image
Mat image1
=
imread
(
"left.jpg"
)
;
Mat image2
=
imread
(
"right.jpg"
)
;
if
(
image1.
empty
(
)
||
image2.
empty
(
)
)
return
1
;
// feature point detection and matching
Ptr
<
Feature2D
detector
=
ORB::
create
(
)
;
vector
<
KeyPoint
keypoints1, keypoints2
;
Mat descriptors1, descriptors2
;
detector
detectAndCompute
(
image1, noArray
(
)
, keypoints1, descriptors1
)
;
detector
detectAndCompute
(
image2, noArray
(
)
, keypoints2, descriptors2
)
;
BFMatcher matcher
(
NORM_HAMMING
)
;
vector
<
DMatch
matches;
matcher.
match
(
descriptors1, descriptors2, matches
)
;
// compute the fundamental matrix
vector
<
Point2f
points1, points2
;
for
(
const
auto
&
match
:
matches
)
{
points1.
push_back
(
keypoints1
[
match.
queryIdx
]
.
pt
)
;
points2.
push_back
(
keypoints2
[
match.
trainIdx
]
.
pt
)
;
}
Mat fundamentalMatrix
=
findFundamentalMat
(
points1, points2, FM_RANSAC
)
;
// output the fundamental matrix
cout
<<
"Fundamental Matrix:\n"
<<
fundamentalMatrix
<<
endl
;
return
0
;
}
6. DNN module
dnn The module provides loading and inference functions for deep learning models.
Main Function
-
Model loading:
-
Supports models from frameworks such as TensorFlow, PyTorch, and Caffe.
Supports models from frameworks such as TensorFlow, PyTorch, and Caffe.
-
Inference:
-
Classify images, perform target detection, semantic segmentation, etc.
Classify images, perform target detection, semantic segmentation, etc.
Example
#include
#include
using
namespace
cv
;
using
namespace
dnn
;
int
main
(
)
{
// load model
Net net
=
readNetFromTensorflow
(
"model.pb"
,
"config.pbtxt"
)
;
// Read image
Mat image
=
imread
(
"test.jpg"
)
;
if
(
image.
empty
(
)
)
return
1
;
// preprocessing
Mat blob
=
blobFromImage
(
image,
1.0
, Size
(
300
,
300
)
, Scalar
(
127.5
,
127.5
,
127.5
)
,
true
,
false
)
;
net.
setInput
(
blob
)
;
// inference
Mat output
=
net.
forward
(
)
;
// process the output
// ...
return
0
;
}