Skip to content

OpenCV

OpenCV Modules

  • Main modules
    • core
    • imgproc
    • imgcodecs
    • videoio
    • highgui
    • video
    • calib3d
    • features2d
    • objdetect
    • ml
    • flann
    • photo
    • stitching
    • cudaarithm
    • cudabgsegm
    • cudacodec
    • cudafeatures2d
    • cudafilters
    • cudaimgproc
    • cudalegacy
    • cudaobjdetect
    • cudaoptflow
    • cudastereo
    • cudawarping
    • cudev
    • shape
    • superres
    • videostab
    • viz
  • Extra modules
    • aruco
    • bgsegm
    • bioinspired
    • ccalib
    • cvv
    • datasets
    • dnn
    • dpm
    • face
    • fuzzy
    • hdf
    • line_descriptor
    • matlab
    • optflow
    • plot
    • reg
    • rgbd
    • saliency
    • sfm
    • stereo
    • structured_light
    • surface_matching
    • text
    • tracking
    • xfeatures2d
    • ximgproc
    • xobjdetect
    • xphoto
  • Other

OpenCV(Open Computer Vision)은 오픈 소스 컴퓨터 비전 C 라이브러리이다. 원래는 인텔이 개발하였다. 윈도, 리눅스 등의 여러 플랫폼에서 사용할 수 있다. 실시간 이미지 프로세싱에 중점을 둔 라이브러리이다. 인텔 CPU에서 사용되는 경우 속도의 향상을 볼 수 있는 Intel Performance Primitives (IPP)를 지원한다.

Category

Main modules

OpenCV: OpenCV modules 페이지에서 아래 내용을 확인할 수 있다.

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
  • videostab - Video Stabilization
  • viz - 3D Visualizer
  • wechat_qrcode - WeChat QR code detector for detecting and parsing QR code.
  • xfeatures2d - Extra 2D Features Framework
  • ximgproc - Extended Image Processing
  • xobjdetect - Extended object detection
  • xphoto - Additional photo processing algorithms

Example

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

CMake options

CMake의 명령행 옵션은 아래와 같다.

-D WITH_CUDA=OFF
CUDA를 사용하지 않는다.
-D ENABLE_PRECOMPILED_HEADERS=OFF
PCH를 사용하지 않는다.
-D WITH_LAPACK=OFF
BLAS의 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
배포용 빌드.
-D CMAKE_INSTALL_PREFIX=/usr/local
설치할 디렉토리 Prefix 설정.

How to install

yum 등을 사용하여 설치할 수 있지만 홈페이지에서 직접 설치할 수 있다.

직접 설치할 경우 library 경로 등이 정상적으로 인식되지 않는 에러가 발생할 수 있다.

./a.out: error while loading shared libraries: libopencv_core.so.2.4: cannot open shared object file: No such file or directory

이 경우 해당 PC에서 LD_LIBRARY_PATH등을 정상적으로 설정했는지 다시 한번 더 확인해야 한다.

highgui 모듈을 사용할 경우 libgtk2.0-dev와 pkg-config를 설치해야 한다. 또한, FFmpeg를 사용할 경우 -fPIC옵션을 사용해야할 수도 있다.

Required build dependencies : Ubuntu

sudo apt-get install cmake
sudo apt-get install gcc g++

to support python2:

sudo apt-get install python-dev python-numpy

to support python3:

sudo apt-get install python3-dev python3-numpy

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:

sudo apt-get install libgtk2.0-dev

to support gtk3:

sudo apt-get install libgtk-3-dev

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 .

OpenCV를 시작하면서 알아야 할 내용

cvCreateImage를 했으면 cdReleaseImage를 해야만 한다.
그래야 메모리 누수를 막을 수 있다.
OpenCV의 컬러 이미지 순서는 B,G,R 이다. 즉 Blue, Green, Red 이다.
보통 우리는 R,G,B로 생각하게 되고, MATLAB의 이미지도 R,G,B 순서이다.
이미지는 좌측하단이 (1.1)
즉 오리진인 경우와 좌측 상단이 (1,1) 인 경우가 있다. MATLAB에서 처리하는 것과 openCV에서 처리하는 것과 보통 우리가 사용하는 Image(jpg, BMP)의 오리진 코디네잇이 다를 수 있다. 결과 이미지가 업사이트 다운 되었다고 말하기 전에 한번 살펴보아라.
업사이드 다운의 해결방안은 cvFlip(IplImage, NULL, 0); 를 이용하면 된다.
이미지의 결과가 90도로 기울어 졌다면
보통 열과 행(너비와 높이)을 거꾸로 계산해서 나오는 경우다.
OpenCV의 많은 함수가 single channel 함수이다. 즉 그레이 이미지만 다룰 수 있다.
따라서 컬러이미지의 경우 3개의 그레이 이미지로 나눈다음 원하는 함수를 적용후 다시 합치면 된다.
보통 나오는 에러메시지가 depth 어쩌구 저쩌구이다. depth는 채널의 깊이이다. 1이면 그레이 이미지 3이면 컬러이미지 4이면 컬러+알파채널이다.

CUDA 사용 방법

우선 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)

GPU에서 동작하는 함수를 사용하여 연산을 수행합니다. 예를 들어, GPU에서 이미지를 그레이스케일로 변환하려면 다음과 같이 할 수 있습니다.

## 1채널로 변환
gray_image = cv2.cuda.cvtColor(d_image, cv2.COLOR_BGR2GRAY)

연산이 끝나면 결과를 다시 호스트 메모리로 복사해야 합니다.

# 결과를 호스트 메모리로 복사
result = gray_image.download()

Example

메르센 트위스터 난수 생성

메르센 트위스터 (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

dist = cv2.pointPolygonTest(cnt,(50,50),True)

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)
[추천] 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 한글 메뉴얼 01 (Unknown user's)
Opencv_kor_manual_01.pdf
OpenCV 한글 메뉴얼 02 (Unknown user's)
Opencv_kor_manual_02.pdf

See also

Favorite site

OpenCV 3.0

OpenCV Study: OpenCV modules

Guide

Tutorials

Example

Streaming

References


  1. OpenCV_TIP_-_Image_Processing_Glossary.pdf 

  2. Multimedia_Systems_-_lossy_compression_techniques.zip 

  3. Microsoft_software_-_based_image_processing_library_OpenCV_2.pdf 

  4. Opencv_iplimage_struct.pdf 

  5. Opencv_basic_struct_and_function.pdf 

  6. Opencv_cvGetQuadrangleSubPix_for_image_rotation.pdf