How to compile basic OpenCV program in C++ in Ubuntu

People new to C++ (and sometimes experienced people) may need to look up how to compile a C++ program with OpenCV.

The following may help them to get the basics right.

Given a a program test.cpp

#include <stdio.h>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

int main(){
    Mat image = Mat::ones(640, 480, CV_8UC1);
    Mat dest;
    image.convertTo(dest, CV_16FC1);
}

compile it with the command

g++ -I/usr/local/include/opencv4 -L/usr/local/lib/ -o test test.cpp -lopencv_dnn -lopencv_ml -lopencv_calib3d -lopencv_imgcodecs -lopencv_video -lopencv_gapi -lopencv_stitching -lopencv_features2d -lopencv_objdetect -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_videoio -lopencv_flann -lopencv_photo

This uses the g++ compiler. (The c++ part of the gcc “gnu compiler collection”).
Check that g++ is installed with

g++ --version

Note the order of the options is critical.
The include directories “-I…” come first. (That is a capital “i” not a lower case “L”.)
Then come the library directories “-L…”
Then the output file “-o test”.
Then the input file “test.cpp”, (i.e. your source code files).
Finally the library files “-l…”. (This is a lower case “L”).

NB Make sure that the “-I” and “-L” directory paths are correct for where the OpenCV header files and libraries are on your computer.