OpenCV
lastmod 2025-05-28created 2014-10-03258 edits
|
OpenCV (Open Computer Vision) is an open-source computer vision C library. It was originally developed by Intel. It can be used on many platforms such as Windows and Linux. It is a library focused on real-time image processing. It supports Intel Performance Primitives (IPP), which can give a speedup when used on Intel CPUs.
Category
- Image processing - Check here for categories organized by keyword.
- OpenCV:Category - OpenCV categories arranged with screenshots.
- OpenCV:Basic - Basics.
- OpenCV:Camera
- OpenCV:Video
- OpenCV:GPU
- OpenCV:Smooth - Smooth
- OpenCV:Histogram
- OpenCV:SVM - How to use Support Vector Machine (SVM)
- OpenCV:FourierTransform or OpenCV:DiscreteFourierTransform
- OpenCV:MachineLearning
- OpenCV:Moments (Image moment)
- OpenCV:KNN
- OpenCV:Stitcher - Image stitching (panorama)
- OpenCV:UMat - GPU acceleration
- OpenCV:CascadeClassifier
- OpenCV:Troubleshooting
- OpenCV:LineType - About the
lineTypeargument used in Drawing. (cv2.LINE_4,cv2.LINE_AA,cv2.LINE_8) - OpenCV:BorderType -
cv2.BORDER_*enums - OpenCV:PedestrianDetection - Pedestrian detection
- OpenCV:QRCodeDetector - QR code detection
- See OpenCV:Python:GStreamer.
- OpenCV-Python
- OpenCV.js
- Integrated Performance Primitives (IPP)
- Matplotlib:Colormap - Colormap code that can be used when drawing objects.
- Interpolation
- Border Extrapolation
- Image Comparison (Compare Images; Korean: 이미지 비교)
- Comparing Two Images in GUI Applications - Explains suitable ways to compare two images in a GUI application.
Main modules
The following can be found on the OpenCV: OpenCV modules page.
- core - Core functionality
- cv::Mat
- cv2.addWeighted - Image blending (used to draw a transparent overlay on top)
- OpenCV:ArithmeticOperations
- cv2.add
- cv2.addWeighted
- cv2.bitwise_and
- cv2.bitwise_or
- cv2.bitwise_xor
- cv2.bitwise_not
- cv::resize
- Thresholding Operations
- cv2.threshold - Image binarization
- Otsu's method - Otsu's binarization algorithm
- cv2.adaptiveThreshold
- cv2.inRange
- cv2.threshold - Image binarization
- Changing Colorspaces
- OpenCV:ColorMaps
- OpenCV:Contours - Contour extraction (a contour is a line connecting the boundaries of regions with similar intensity)
- Contour Features
- cv2.arcLength - Returns the contour length.
- cv2.contourArea - Returns the area of the region enclosed by the contour.
- cv2.boundingRect -Returns the minimum-size rectangle (bounding box) enclosing the given points.
- cv2.minEnclosingCircle - Returns the minimum-size circle enclosing the given points.
- cv2.minAreaRect - Returns the minimum-size rotated rectangle enclosing the given points.
- cv2.minEnclosingTriangle - Returns the minimum-size triangle enclosing the given points.
- cv2.approxPolyDP - Approximates (simplifies) a contour.
- cv2.fitEllipse - Returns the ellipse that fits the given points.
- cv2.fitLine - Returns the straight line that fits the given points.
- Convex Hull
- cv2.convexHull - Returns the convex hull (connecting the outermost points) of the given points.
- cv2.convexityDefects - Returns the convexity defects from the given points and convex hull.
- cv2.isContourConvex - Checks whether it is convex.
- Contour Features
- OpenCV:Drawing - How to draw.
- cv2.arrowedLine
- cv2.circle
- cv2.clipLine
- cv2.drawContours
- cv2.drawMarker
- cv2.ellipse2Poly
- cv2.ellipse
- cv2.fillConvexPoly
- cv2.fillPoly
- cv2.getFontScaleFromHeight
- cv2.getTextSize
- cv2.line
- cv2.polylines
- cv2.putText
- cv2.rectangle
- OpenCV:EdgeDetection - Edge detection
- Geometric Transformations of Images
- Affine Transformation
- cv2.getAffineTransform
- cv2.warpAffine
- Perspective Transformation
- Affine Transformation
- Hough Line Transform
- Hough Circle Transform
- OpenCV:BackgroundSubtraction - Background extraction
- Feature Detection and Description
- SIFT
- SURF
- MSER
- FAST
- Oriented FAST and rotated BRIEF (ORB)
- BRISK
- MRRID
- MROGH
- LIOP
- BRIEF
- cvGoodFeatureToTrack
- Descriptor Matchers (Feature matching)
- Fast Library for Approximate Nearest Neighbors (FLANN)
- Brute-Force Matching
- Accelerated-KAZE Features (AKAZE)
- Drawing Function of Keypoints and Matches
- Object Categorization
- Hardware Acceleration Layer
- OpenCV:PedestrianDetection - Pedestrian detection
- Cascade Classifier
Extra modules
- alphamat - Alpha Matting
- aruco - ArUco Marker Detection
- barcode - Barcode detecting and decoding methods
- bgsegm - Improved Background-Foreground Segmentation Methods
- bioinspired - Biologically inspired vision models and derivated tools
- ccalib - Custom Calibration Pattern for 3D reconstruction
- cudaarithm - Operations on Matrices
- cudabgsegm - Background Segmentation
- cudacodec - Video Encoding/Decoding
- cudafeatures2d - Feature Detection and Description
- cudafilters - Image Filtering
- cudaimgproc - Image Processing
- cudalegacy - Legacy support
- cudaobjdetect - Object Detection
- cudaoptflow - Optical Flow
- cudastereo - Stereo Correspondence
- cudawarping - Image Warping
- cudev - Device layer
- cvv - GUI for Interactive Visual Debugging of Computer Vision Programs
- datasets - Framework for working with different datasets
- dnn_objdetect - DNN used for object detection
- dnn_superres - DNN used for super resolution
- dpm - Deformable Part-based Models
- face - Face Analysis
- freetype - Drawing UTF-8 strings with freetype/harfbuzz
- fuzzy - Image processing based on fuzzy mathematics
- hdf - Hierarchical Data Format I/O routines
- hfs - Hierarchical Feature Selection for Efficient Image Segmentation
- img_hash - The module brings implementations of different image hashing algorithms.
- intensity_transform - The module brings implementations of intensity transformation algorithms to adjust image contrast.
- julia - Julia bindings for OpenCV
- line_descriptor - Binary descriptors for lines extracted from an image
- mcc - Macbeth Chart module
- optflow - Optical Flow Algorithms
- ovis - OGRE 3D Visualiser
- phase_unwrapping - Phase Unwrapping API
- plot - Plot function for Mat data
- quality - Image Quality Analysis (IQA) API
- rapid - silhouette based 3D object tracking
- reg - Image Registration
- rgbd - RGB-Depth Processing
- saliency - Saliency API
- sfm - Structure From Motion
- shape - Shape Distance and Matching
- stereo - Stereo Correspondance Algorithms
- structured_light - Structured Light API
- superres - Super Resolution
- surface_matching - Surface Matching
- text - Scene Text Detection and Recognition
- tracking - Tracking API
Example
- OpenCV:Example:CarCounting: Separates car objects in a video and counts them.
- OpenCV:Example:DrawRois
- OpenCV:Example:Tkinter - How to draw OpenCV on Python:Tkinter
- OpenCV:Example:Blending - Image compositing
- OpenCV:Example:CropCenter - Cropping an image around its center, usable with both numpy and PIL formats.
- OpenCV:Example:ObjectAngleTracking - Example of tracking an object and finding its angle (used in ddrm)
- OpenCV:Example:IronPlateCamber - Measuring steel plate camber (Camber; bending)
- OpenCV:Example:IronPlateAngle - Measuring steel plate rotation angle
- Detectron2:Visualization - Python code that draws Predict results from Detectron2. Uses the OpenCV Drawing API.
- Footfall: A Camera Based People Counting System for under £60
- MaskRCNN:Example:VideoReadWrite: Video Read & Write Python example for the Mask R-CNN demo.
Libraries
- cvui
- ImageZMQ
- imageflow - High-performance image manipulation for web servers.
- OpenVINO - OpenVINO is an open-source toolkit for optimizing and deploying deep learning models. It provides boosted deep learning performance for vision, audio, and language models from popular frameworks like TensorFlow, PyTorch, and more. - https://docs.openvino.ai/latest/home.html
Graph-based GUI
- MediaPipe - MediaPipe offers open source cross-platform, customizable ML solutions for live and streaming media. - https://mediapipe.dev/
- Cloud Vision - Build Computer Vision Application in the Browser - https://cloudvision.app/image.html
- BFH ImagePlay - Rapid Prototyping for Image Processing - http://cpvrlab.github.io/ImagePlay/
- ImprovCV - ImprovCV is a portable, open source, modular computer vision system that enables rapid, interactive computer vision development. - http://www.adrianboeing.com/improvCV/
CMake options
- Compile OpenCV without GPU?
- Can't Write in PCH file crunchbang
- [Recommended] OpenCV: OpenCV configuration options reference
The CMake command-line options are as follows.
-
-D WITH_CUDA=OFF - Do not use CUDA.
-
-D ENABLE_PRECOMPILED_HEADERS=OFF - Do not use PCH.
-
-D WITH_LAPACK=OFF - Do not use BLAS's LAPACK.
- libopencv_core.so.3.2.0: undefined reference to 'dpotrf_' #7970
Build tests, samples and applications
There are two kinds of tests: accuracy (opencv_test_*) and performance (opencv_perf_*). Tests and applications are enabled by default. Examples are not being built by default and should be enabled explicitly.
Corresponding cmake options:
cmake \
-DBUILD_TESTS=ON \
-DBUILD_PERF_TESTS=ON \
-DBUILD_EXAMPLES=ON \
-DBUILD_opencv_apps=ON \
../opencv
CMake default options
-
-D CMAKE_BUILD_TYPE=RELEASE - Release build.
-
-D CMAKE_INSTALL_PREFIX=/usr/local - Sets the installation directory prefix.
How to install
You can install it with yum and the like, but you can also install it directly from the homepage.
When installing it yourself, errors may occur where the library path and the like are not recognized properly.
./a.out: error while loading shared libraries: libopencv_core.so.2.4: cannot open shared object file: No such file or directory
In this case, double-check that LD_LIBRARY_PATH and the like are set correctly on that PC.
When using the highgui module, you need to install libgtk2.0-dev and pkg-config. Also, when using FFmpeg, you may need to use the -fPIC option.
Required build dependencies : Ubuntu
to support python2:
to support python3:
Next we need GTK support for GUI features, Camera support (v4l), Media Support (ffmpeg, gstreamer) etc.
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev
sudo apt-get install libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev
to support gtk2:
to support gtk3:
Optional Dependencies
Above dependencies are sufficient to install OpenCV in your Ubuntu machine. But depending upon your requirements, you may need some extra dependencies. A list of such optional dependencies are given below. You can either leave it or install it, your call :)
OpenCV comes with supporting files for image formats like PNG, JPEG, JPEG2000, TIFF, WebP etc. But it may be a little old. If you want to get latest libraries, you can install development files for system libraries of these formats.
sudo apt-get install libpng-dev
sudo apt-get install libjpeg-dev
sudo apt-get install libopenexr-dev
sudo apt-get install libtiff-dev
sudo apt-get install libwebp-dev
Installation in Linux
# Install minimal prerequisites (Ubuntu 18.04 as reference)
sudo apt update && sudo apt install -y cmake g++ wget unzip
# Download and unpack sources
wget -O opencv.zip https://github.com/opencv/opencv/archive/4.x.zip
unzip opencv.zip
# Create build directory
mkdir -p build && cd build
# Configure
cmake ../opencv-4.x
# Build
cmake --build .
Things to know when starting with OpenCV
- If you call
cvCreateImage, you must callcdReleaseImage. - That is how you prevent memory leaks.
- OpenCV's color image order is B,G,R, that is, Blue, Green, Red.
- We usually think in R,G,B, and MATLAB images are also in R,G,B order.
- In an image, the bottom left is (1.1)
- That is, there are cases where it is the origin and cases where the top left is (1,1). The origin coordinates may differ between processing in MATLAB, processing in openCV, and the
Image(jpg, BMP)we usually use. Check this before saying the result image came out upside down. - To fix an upside-down image, use
cvFlip(IplImage, NULL, 0);.
- If the resulting image is tilted by 90 degrees
- This usually happens when columns and rows (width and height) are computed the other way around.
- Many OpenCV functions are single channel functions, that is, they can only handle gray images.
- So for a color image, split it into 3 gray images, apply the function you want, and merge them back.
- The usual error message says something about depth. depth is the depth of the channels: 1 is a gray image, 3 is a color image, and 4 is color + alpha channel.
How to use CUDA
First, it must be compiled with the option to use CUDA.
import cv2
import numpy as np
# Numpy 배열 생성
image = np.zeros((512, 512, 3), dtype=np.uint8)
# Numpy 배열을 GPU 메모리로 복사
d_image = cv2.cuda_GpuMat()
d_image.upload(image)
Perform operations using functions that run on the GPU. For example, to convert an image to grayscale on the GPU, you can do the following.
When the operations are done, you need to copy the result back to host memory.
Example
Mersenne Twister random number generation
Example of generating random numbers with Mersenne Twister (MT19937):
cv::RNG_MT19937 rng;
for (int i = 0; i < hulls.size(); ++i) {
cv::drawContours(image, hulls, i, cv::Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255)), CV_FILLED);
}
Collision check
Version check
With OpenCV 2.4.x: You can use CV_VERSION or CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION from a C/C++ simple program.
#include <stdio.h>
#include <cv.h>
int main(void)
{
printf("%s\r\n", CV_VERSION);
printf("%u.%u.%u\r\n", CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION);
}
Documentations
- Welcome to OpenCV-Python Tutorials’s documentation!
- https://opencv-python-tutroals.readthedocs.io/en/latest/
- Opencv-python-tutroals_2019-03-07.zip (2019-03-07)
- [Recommended] OpenCV-Python Study documentation!
- https://opencv-python.readthedocs.io/en/latest/index.html
- OpenCV-Python_Study_documentation_2018-11-21.zip (2018-11-21)
- OpenCV Korean manual 01 (Unknown user's)
-
Opencv_kor_manual_01.pdf
- OpenCV Korean manual 02 (Unknown user's)
-
Opencv_kor_manual_02.pdf
See also
- Leptonica
- Caffe:Python
- Dlib
- GRIP - Program for rapidly developing computer vision applications
Favorite site
- OpenCV web site
- Wikipedia (en) description of OpenCV
- Installing OpenCV and building (compiling) with CMake GPU+TBB+IPP
- Image processing glossary 1
- Multimedia systems: lossy compression techniques 2
- Micro Software - Image processing with the OpenCV library 2 3
- [Recommended] OpenCV Korean Wiki Project
- [Recommended] OpenCV-Python Study documentation! — gramman 0.1 documentation - Added to #Documentations
- Korea's best computer vision community
- OpenCV tutorial: inserting a video into a marker
OpenCV 3.0
OpenCV Study: OpenCV modules
Guide
- Explanation of the IplImage struct
- OpenCV Tutorial 2 - Chapter 3
- IplImage struct 4
- Basic structs and image functions among operations 5
- Image rotation in MFC using OpenCV's cvGetQuadrangleSubPix 6
Tutorials
- OpenCV4 | 076923 Documentation
- OpenCV-Python Study documentation! — gramman 0.1 documentation
- C# OpenCvSharp2 tutorial: Lesson 1 - Installing OpenCvSharp2 - YUN DAE HEE
Example
- Template Matching with OpenCV
- OpenCV #1 Displaying an image
- OpenCV image display example
- OpenCV Example: Running simple image arithmetic operations
- OpenCV #7-2 Example (detecting lines in an image with the Hough transform)
- Digital image processing - Filter part #1
- Converting cv::Mat to SDL_Texture
Streaming
References
- Affine transformation
- Anti-Glare
- Artificial neural network
- Atmospheric correction
- Automatic number-plate recognition
- Avplayer
- Border Extrapolation
- C++
- Caffe
- Camshift
- Canny edge detector
- Cascading classifiers
- Cbp-translate
- Computer Vision Annotation Tool
- Connected Components
- Contours
- Convolution
- Convolutional neural network
- CUDA
- Curriculum
- Cv2.absdiff
- Cv2.accumulateWeighted
- Cv2.adaptiveThreshold
- Cv2.addWeighted
- Cv2.calcHist
- Cv2.createThinPlateSplineShapeTransformer
- Cv2.cvtColor
- Cv2.filter2D
- Cv2.findContours
- Cv2.HoughCircles
- Cv2.HoughLines
- Cv2.HoughLinesP
- Cv2.inRange
- Cv2.matchShapes
- Cv2.threshold
- Cv2.TrackerBoosting create
- Cv2.TrackerCSRT create
- Cv2.TrackerGOTURN create
- Cv2.TrackerKCF create
- Cv2.TrackerMedianFlow create
- Cv2.TrackerMIL create
- Cv2.TrackerMOSSE create
- Cv2.TrackerTLD create
- Cv2.VideoCapture
- Cv2.VideoWriter
- Cv2.warpPolar
- Cv::Mat
- Cv::Mat:Python
- Cv::resize
- CvCapture
- Deblurring
- Deep learning
- Dehazing
- Detectron2:Visualization
- Digital image processing
- Distorting mirror
- Face recognition
- Facial recognition system
- Fast Library for Approximate Nearest Neighbors
- Feature detection
and 91 more