OpenCV
|
OpenCV(Open Computer Vision)은 오픈 소스 컴퓨터 비전 C 라이브러리이다. 원래는 인텔이 개발하였다. 윈도, 리눅스 등의 여러 플랫폼에서 사용할 수 있다. 실시간 이미지 프로세싱에 중점을 둔 라이브러리이다. 인텔 CPU에서 사용되는 경우 속도의 향상을 볼 수 있는 Intel Performance Primitives (IPP)를 지원한다.
Category
- Image processing - Keyword 에 맞춘 카테고리는 이 곳에서 확인.
- OpenCV:Category - 스크린샷과 함께 보는 OpenCV 카테고리 정렬.
- OpenCV:Basic - 기초.
- OpenCV:Camera
- OpenCV:Video
- OpenCV:GPU
- OpenCV:Smooth - Smooth
- OpenCV:Histogram
- OpenCV:SVM - Support Vector Machine (SVM) 사용 방법
- OpenCV:FourierTransform or OpenCV:DiscreteFourierTransform
- OpenCV:MachineLearning
- OpenCV:Moments (Image moment)
- OpenCV:KNN
- OpenCV:Stitcher - 이미지 스티칭 (파노라마)
- OpenCV:UMat - GPU 가속
- OpenCV:CascadeClassifier
- OpenCV:Troubleshooting
- OpenCV:LineType - Drawing 에서 사용되는
lineType
인자에 대한 내용. (cv2.LINE_4
,cv2.LINE_AA
,cv2.LINE_8
) - OpenCV:BorderType -
cv2.BORDER_*
enums - OpenCV:PedestrianDetection - 보행자 검출
- OpenCV:QRCodeDetector - QR 코드 검출
- OpenCV:Python:GStreamer 참조.
- OpenCV-Python
- OpenCV.js
- Integrated Performance Primitives (IPP)
- Matplotlib:Colormap - 객체를 그릴 때 사용할 수 있는 색상 테이블 (Colormap) 코드.
- 보간법 (Interpolation)
- 외삽 보간법 (Border Extrapolation)
- Image Comparison (Compare Images; 이미지 비교)
- Comparing Two Images in GUI Applications - GUI 어플리케이션으로 두 장의 이미지를 비교하는 적합한 방법 설명.
Main modules
OpenCV: OpenCV modules 페이지에서 아래 내용을 확인할 수 있다.
- core - Core functionality
- cv::Mat
- cv2.addWeighted - 이미지 블랜딩 (투명한 오버레이 그림을 덮어 그릴 때 사용)
- OpenCV:ArithmeticOperations
- cv2.add
- cv2.addWeighted
- cv2.bitwise_and
- cv2.bitwise_or
- cv2.bitwise_xor
- cv2.bitwise_not
- cv::resize
- Thresholding Operations
- cv2.threshold - 영상 이진화
- Otsu's method - 오츠 이진화 알고리즘
- cv2.adaptiveThreshold
- cv2.inRange
- cv2.threshold - 영상 이진화
- Changing Colorspaces
- OpenCV:ColorMaps
- OpenCV:Contours - 윤곽선(유사한 강도를 가지고 있는 영역의 경계선을 연결한 선) 추출
- Contour Features
- cv2.arcLength - 외곽선 길이를 반환합니다.
- cv2.contourArea - 외곽선이 감싸는 영역의 면적을 반환합니다.
- cv2.boundingRect -주어진 점을 감싸는 최소 크기 사각형(바운딩 박스)를 반환합니다.
- cv2.minEnclosingCircle - 주어진 점을 감싸는 최소 크기 원을 반환합니다.
- cv2.minAreaRect - 주어진 점을 감싸는 최소 크기 회전된 사각형을 반환합니다.
- cv2.minEnclosingTriangle - 주어진 점을 감싸는 최소 크기 삼각형을 반환합니다.
- cv2.approxPolyDP - 외곽선을 근사화(단순화) 합니다.
- cv2.fitEllipse - 주어진 점에 적합한 타원을 반환합니다.
- cv2.fitLine - 주어진 점에 적합한 직선을 반환합니다.
- Convex Hull
- cv2.convexHull - 주어진 점으로부터 컨벡스 헐(최외곽 점들을 연결)을 반환합니다.
- cv2.convexityDefects - 주어진 점과 컨벡스 헐로부터 컨벡스 디펙트를 반환합니다.
- cv2.isContourConvex - 컨벡스 인지를 검사합니다.
- Contour Features
- OpenCV:Drawing - Drawing 방법.
- 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
- 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
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: 동영상에서 자동차 객체를 분리하고 카운팅 한다.
- OpenCV:Example:DrawRois
- OpenCV:Example:Tkinter - OpenCV를 Python:Tkinter에 그리는 방법
- OpenCV:Example:Blending - 이미지 합성
- OpenCV:Example:CropCenter - numpy 형식 및 PIL 형식 모두 사용 가능한, 중심을 기준으로 이미지 자르기.
- OpenCV:Example:ObjectAngleTracking - 객체를 추적하고 각도를 구하는 예제 (ddrm에서 사용)
- OpenCV:Example:IronPlateCamber - 철판 캠버(Camber; 휘어짐) 측정
- OpenCV:Example:IronPlateAngle - 철판 회전 각도 측정
- Detectron2:Visualization - Detectron2에서 Predict 결과를 그리는 Python 코드. OpenCV의 Drawing API를 사용한다.
- Footfall: A Camera Based People Counting System for under £60
- MaskRCNN:Example:VideoReadWrite: Mask R-CNN 데모를 위한 Video Read & Write Python 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
- 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
- [추천] OpenCV: OpenCV configuration options reference
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
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 .
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에서 이미지를 그레이스케일로 변환하려면 다음과 같이 할 수 있습니다.
연산이 끝나면 결과를 다시 호스트 메모리로 복사해야 합니다.
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
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
- Leptonica
- Caffe:Python
- Dlib
- GRIP - Program for rapidly developing computer vision applications
Favorite site
- OpenCV web site
- Wikipedia (en) OpenCV에 대한 설명
- OpenCV 설치 및 CMake GPU+TBB+IPP 빌드(컴파일)하기
- 영상처리 용어해설 1
- 멀티미디어시스템: 손실 압축 기법 2
- 마이크로 소프트웨어 - OpenCV 라이브러리를 이용한 영상처리 2 3
- [추천] OpenCV 한글 Wiki Project
- [추천] OpenCV-Python Study documentation! — gramman 0.1 documentation - #Documentations에 추가함
- 대한민국 최고의 컴퓨터비젼 커뮤니티
- OpenCV 강좌: 마커에 동영상 삽입하기
OpenCV 3.0
OpenCV Study: OpenCV modules
Guide
- IplImage 구조체에 대한 설명
- OpenCV Tutorial 2 - Chapter 3
- IplImage 구조체 4
- 기본 구조체와 연산중 이미지 함수 5
- MFC에서 OpenCV의 cvGetQuadrangleSubPix를 이용한 이미지 회전 6
Tutorials
- OpenCV4 | 076923 Documentation
- OpenCV-Python Study documentation! — gramman 0.1 documentation
- C# OpenCvSharp2 강좌 : 제 1강 - OpenCvSharp2 설치 - YUN DAE HEE
Example
- OpenCV 를 이용한 템플릿 매칭(Template Matching) 하기
- OpenCV #1 이미지 출력
- OpenCV 이미지 출력 예제
- OpenCV Example: 간단한 연상 산술 연산 실행
- OpenCV #7-2 Example (허프 변환으로 영상 내 선 감지)
- 디지털 영상처리 - Filter 편 #1
- Converting cv::Mat to SDL_Texture