# OpenCV with C++

# OpenCV + CLion + C++

Youtube - Configuring OpenCV + CLion + C++ on Ubuntu

# Instalation

Download from the GitHub page, at the releases tab, the opencv_contrib and, OpenCV and Cmake to buil both.

OpenCV opencv-contrib Cmake

With the Cmake install a binary version for windows, double click to install. Piece of cake.

Create a folder at C: and copy, then crate a build folder inside the opencv-4.3.0

Open Cmake as administrator and Browse source C:/Program Files/OpenCV/opencv-4.3.0 and Browse build C:/Program Files/OpenCV/opencv-4.3.0/build, then Configure.





Look for OpenCV extra modules...



Select C:/Program Files/OpenCV/opencv_contrib-4.3.0/modules, then Generate.



Detected processor: AMD64
Found PythonInterp: C:/Users/Thiago Souto/AppData/Local/Programs/Python/Python37-32/python.exe (found suitable version "3.7.4", minimum required is "2.7") 
libjpeg-turbo: VERSION = 2.0.4, BUILD = opencv-4.3.0-libjpeg-turbo
Could NOT find OpenJPEG (minimal suitable version: 2.0, recommended version >= 2.3.1)
found Intel IPP (ICV version): 2020.0.0 [2020.0.0 Gold]
at: C:/Program Files/OpenCV/opencv-4.3.0/build/3rdparty/ippicv/ippicv_win/icv
found Intel IPP Integration Wrappers sources: 2020.0.0
at: C:/Program Files/OpenCV/opencv-4.3.0/build/3rdparty/ippicv/ippicv_win/iw
Could not find OpenBLAS include. Turning OpenBLAS_FOUND off
Could not find OpenBLAS lib. Turning OpenBLAS_FOUND off
Could NOT find BLAS (missing: BLAS_LIBRARIES) 
LAPACK requires BLAS
A library with LAPACK API not found. Please specify library location.
Could NOT find JNI (missing: JAVA_AWT_LIBRARY JAVA_JVM_LIBRARY JAVA_INCLUDE_PATH JAVA_INCLUDE_PATH2 JAVA_AWT_INCLUDE_PATH) 
VTK is not found. Please set -DVTK_DIR in CMake to VTK build directory, or to VTK install subdirectory with VTKConfig.cmake file
OpenCV Python: during development append to PYTHONPATH: C:/Program Files/OpenCV/opencv-4.3.0/build/python_loader
Module opencv_alphamat disabled because the following dependencies are not found: Eigen
Caffe:   NO
Protobuf:   NO
Glog:   NO
freetype2:   NO
harfbuzz:    NO
Module opencv_ovis disabled because OGRE3D was not found
No preference for use of exported gflags CMake configuration set, and no hints for include/library directories provided. Defaulting to preferring an installed/exported gflags CMake configuration if available.
Failed to find installed gflags CMake configuration, searching for gflags build directories exported with CMake.
Failed to find gflags - Failed to find an installed/exported CMake configuration for gflags, will perform search for installed gflags components.
Failed to find gflags - Could not find gflags include directory, set GFLAGS_INCLUDE_DIR to directory containing gflags/gflags.h
Failed to find glog - Could not find glog include directory, set GLOG_INCLUDE_DIR to directory containing glog/logging.h
Module opencv_sfm disabled because the following dependencies are not found: Eigen Glog/Gflags
Tesseract:   NO
Allocator metrics storage type: 'long long'
Registering hook 'INIT_MODULE_SOURCES_opencv_dnn': C:/Program Files/OpenCV/opencv-4.3.0/modules/dnn/cmake/hooks/INIT_MODULE_SOURCES_opencv_dnn.cmake
opencv_dnn: filter out cuda4dnn source code
xfeatures2d/boostdesc: Download: boostdesc_bgm.i
xfeatures2d/boostdesc: Download: boostdesc_bgm_bi.i
xfeatures2d/boostdesc: Download: boostdesc_bgm_hd.i
xfeatures2d/boostdesc: Download: boostdesc_binboost_064.i
xfeatures2d/boostdesc: Download: boostdesc_binboost_128.i
xfeatures2d/boostdesc: Download: boostdesc_binboost_256.i
xfeatures2d/boostdesc: Download: boostdesc_lbgm.i
xfeatures2d/vgg: Download: vgg_generated_48.i
xfeatures2d/vgg: Download: vgg_generated_64.i
xfeatures2d/vgg: Download: vgg_generated_80.i
xfeatures2d/vgg: Download: vgg_generated_120.i
data: Download: face_landmark_model.dat

General configuration for OpenCV 4.3.0 =====================================
  Version control:               unknown

  Extra modules:
    Location (extra):            C:/Program Files/OpenCV/opencv_contrib-4.3.0/modules
    Version control (extra):     unknown

  Platform:
    Timestamp:                   2020-04-11T08:36:47Z
    Host:                        Windows 10.0.18362 AMD64
    CMake:                       3.17.1
    CMake generator:             Visual Studio 16 2019
    CMake build tool:            C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/MSBuild/Current/Bin/MSBuild.exe
    MSVC:                        1924

  CPU/HW features:
    Baseline:                    SSE SSE2 SSE3
      requested:                 SSE3
    Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX
      requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
      SSE4_1 (16 files):         + SSSE3 SSE4_1
      SSE4_2 (2 files):          + SSSE3 SSE4_1 POPCNT SSE4_2
      FP16 (1 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX
      AVX (5 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
      AVX2 (30 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
      AVX512_SKX (6 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX

  C/C++:
    Built as dynamic libs?:      YES
    C++ standard:                11
    C++ Compiler:                C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.24.28314/bin/Hostx64/x64/cl.exe  (ver 19.24.28316.0)
    C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /MP  /MD /O2 /Ob2 /DNDEBUG 
    C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /MP  /MDd /Zi /Ob0 /Od /RTC1 
    C Compiler:                  C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.24.28314/bin/Hostx64/x64/cl.exe
    C flags (Release):           /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /MP   /MD /O2 /Ob2 /DNDEBUG 
    C flags (Debug):             /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /MP /MDd /Zi /Ob0 /Od /RTC1 
    Linker flags (Release):      /machine:x64  /INCREMENTAL:NO 
    Linker flags (Debug):        /machine:x64  /debug /INCREMENTAL 
    ccache:                      NO
    Precompiled headers:         YES
    Extra dependencies:
    3rdparty dependencies:

  OpenCV modules:
    To be built:                 aruco bgsegm bioinspired calib3d ccalib core datasets dnn dnn_objdetect dnn_superres dpm face features2d flann fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor ml objdetect optflow phase_unwrapping photo plot quality rapid reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab xfeatures2d ximgproc xobjdetect xphoto
    Disabled:                    world
    Disabled by dependency:      -
    Unavailable:                 alphamat cnn_3dobj cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv freetype hdf java js matlab ovis python2 python3 sfm viz
    Applications:                tests perf_tests apps
    Documentation:               NO
    Non-free algorithms:         NO

  Windows RT support:            NO

  GUI: 
    Win32 UI:                    YES
    VTK support:                 NO

  Media I/O: 
    ZLib:                        build (ver 1.2.11)
    JPEG:                        build-libjpeg-turbo (ver 2.0.4-62)
    WEBP:                        build (ver encoder: 0x020f)
    PNG:                         build (ver 1.6.37)
    TIFF:                        build (ver 42 - 4.0.10)
    JPEG 2000:                   build Jasper (ver 1.900.1)
    OpenEXR:                     build (ver 2.3.0)
    HDR:                         YES
    SUNRASTER:                   YES
    PXM:                         YES
    PFM:                         YES

  Video I/O:
    DC1394:                      NO
    FFMPEG:                      YES (prebuilt binaries)
      avcodec:                   YES (58.54.100)
      avformat:                  YES (58.29.100)
      avutil:                    YES (56.31.100)
      swscale:                   YES (5.5.100)
      avresample:                YES (4.0.0)
    GStreamer:                   NO
    DirectShow:                  YES
    Media Foundation:            YES
      DXVA:                      YES

  Parallel framework:            Concurrency

  Trace:                         YES (with Intel ITT)

  Other third-party libraries:
    Intel IPP:                   2020.0.0 Gold [2020.0.0]
           at:                   C:/Program Files/OpenCV/opencv-4.3.0/build/3rdparty/ippicv/ippicv_win/icv
    Intel IPP IW:                sources (2020.0.0)
              at:                C:/Program Files/OpenCV/opencv-4.3.0/build/3rdparty/ippicv/ippicv_win/iw
    Lapack:                      NO
    Eigen:                       NO
    Custom HAL:                  NO
    Protobuf:                    build (3.5.1)

  OpenCL:                        YES (NVD3D11)
    Include path:                C:/Program Files/OpenCV/opencv-4.3.0/3rdparty/include/opencl/1.2
    Link libraries:              Dynamic load

  Python (for build):            C:/Users/Thiago Souto/AppData/Local/Programs/Python/Python37-32/python.exe

  Java:                          
    ant:                         NO
    JNI:                         NO
    Java wrappers:               NO
    Java tests:                  NO

  Install to:                    C:/Program Files/OpenCV/opencv-4.3.0/build/install
-----------------------------------------------------------------

Configuring done
Generating done
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

Then run the OpenCV vs code file in Visual Studio Code.

Build OpenCV on MSVS, 6:11

WARNING

finish later

TIP

This one should work

# Ubuntu Instalation

Video for Ubuntu installation

# Loading and showing an Image in C++

In OpenCV 3 we have multiple modules. Each one takes care of a different area or approach towards image processing. You could already observe this in the structure of the user guide of these tutorials itself. Before you use any of them you first need to include the header files where the content of each individual module is declared.

You'll almost always end up using the:

  • core section, as here are defined the basic building blocks of the library
  • imgcodecs module, which provides functions for reading and writing
  • highgui module, as this contains the functions to show an image in a window

We also include the iostream to facilitate console line output and input.

By declaring using namespace cv;, in the following, the library functions can be accessed without explicitly stating the namespace.

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>

using namespace cv;
1
2
3
4
5
6

Now, let's analyze the main code. As a first step, we read the image "Andromeda.jpg" from the samples folder. In order to do so, a call to the cv::imread function loads the image using the file path specified by the first argument. The second argument is optional and specifies the format in which we want the image. This may be:

  • IMREAD_COLOR loads the image in the BGR 8-bit format. This is the default that is used here.
  • IMREAD_UNCHANGED loads the image as is (including the alpha channel if present)
  • IMREAD_GRAYSCALE loads the image as an intensity one

After reading in the image data will be stored in a cv::Mat object.

int main() {
    std::string image_path = ("/home/thiago/CLionProjects/OpenCV-test/samples/Andromeda.jpg");
    Mat img = imread(image_path, IMREAD_COLOR);
1
2
3

WARNING

OpenCV offers support for the image formats Windows bitmap (bmp), portable image formats (pbm, pgm, ppm) and Sun raster (sr, ras). With help of plugins (you need to specify to use them if you build yourself the library, nevertheless in the packages we ship present by default) you may also load image formats like JPEG (jpeg, jpg, jpe), JPEG 2000 (jp2 - codenamed in the CMake as Jasper), TIFF files (tiff, tif) and portable network graphics (png). Furthermore, OpenEXR is also a possibility.

Afterwards, a check is executed, if the image was loaded correctly.

if (img.empty()) {
        std::cout << "Could not read the image: " << image_path << std::endl;
        return 1;
    }
1
2
3
4

Then, the image is shown using a call to the cv::imshow function. The first argument is the title of the window and the second argument is the cv::Mat object that will be shown.

Because we want our window to be displayed until the user presses a key (otherwise the program would end far too quickly), we use the cv::waitKey function whose only parameter is just how long should it wait for a user input (measured in milliseconds). Zero means to wait forever. The return value is the key that was pressed.

    imshow("Display window", img);
    int k = waitKey(0); // Wait for a keystroke in the window
1
2

In the end, the image is written to a file if the pressed key was the "s"-key. For this the cv::imwrite function is called that has the file path and the cv::Mat object as an argument.

if (k == 's') {
        imwrite("Andromeda.png", img);
    }
1
2
3

here is the full code:

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main() {
    std::string image_path = ("/home/thiago/CLionProjects/OpenCV-test/samples/Andromeda.jpg");
    Mat img = imread(image_path, IMREAD_COLOR);
    if (img.empty()) {
        std::cout << "Could not read the image: " << image_path << std::endl;
        return 1;
    }
    imshow("Display window", img);
    int k = waitKey(0); // Wait for a keystroke in the window
    if (k == 's') {
        imwrite("Andromeda.png", img);
    }
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# Cmake

cmake_minimum_required(VERSION 3.16)
project(OpenCV_test)

set(CMAKE_CXX_STANDARD 14)

find_package(OpenCV REQUIRED)

SET(SOURCE_FILES main.cpp)
add_executable(OpenCV_test main.cpp)

INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(OpenCV_test ${OpenCV_LIBS})
1
2
3
4
5
6
7
8
9
10
11
12

# Resize an image

resize

Include the opencv library create another Mat Mat img_scaled;




 







 
 













#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main() {
    std::string image_path = ("/home/thiago/CLionProjects/OpenCV-test/samples/Andromeda.jpg");
    Mat img = imread(image_path, IMREAD_COLOR);
    Mat img_scaled;
    resize(img, img_scaled, Size(800,600), 0.5, 0.5, INTER_LINEAR);

    if (img.empty()) {
        std::cout << "Could not read the image: " << image_path << std::endl;
        return 1;
    }
    imshow("Display window", img_scaled);
    int k = waitKey(0); // Wait for a keystroke in the window
    if (k == 's') {
        imwrite("Andromeda_SCALED.png", img_scaled);
    }
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# Yolov4

git clone https://github.com/AlexeyAB/darknet.git

cd darknet

make

wget https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.weights