6

I have installed OpenCV 4.4 with pip (pip3 install opencv-python), which works great from python.

However I would now like to switch to C++ (both to learn and to see what performance gain I can get), for example to execute this but I do not know how to compile it properly with g++, to include OpenCV's headers.

Running cv2.__file gives me '.../.local/lib/python3.8/site-packages/cv2/cv2.cpython-38-x86_64-linux-gnu.so'.

I would prefer to use only g++ rather than tools like CMakeList, if possible, to understand exactly what I am doing. Being new to the C++ world, I admit that I am a bit confused about the whoe building and linking process. Any help would be greatly appreciated ;)

Big Bro
  • 797
  • 3
  • 12
  • 1
    The fact that you installed the opencv python wheel with pip is totally irrelevant here. Download the source code and build opencv (with cmake!). Follow any recent tutorial out there. – Miki Oct 26 '20 at 16:34
  • 2
    So I cannot use the binary which comes with pip (the `*.so`) ? That seems weird. – Big Bro Oct 26 '20 at 21:42

1 Answers1

1

I was also trying to do the same thing and it is possible to do if you really want :) the command I used to compile is the following:

g++ -g {file} -o {fileBasenameNoExtension} `pkg-config --cflags --libs opencv4`

However you will probably not have the package opencv4 recognized out of the box if it was installed with pip. Therefore you have to define the path to the package file opencv4.pc by adding the path to that file to PKG_CONFIG_PATH environment variable. Mine was:

  • */home/{user}/anaconda3/pkgs/opencv-4.6.0-py39hd653453_2/lib/pkgconfig"

If anyone would like to use the CMakeList there is also a way. Check out the https://stackoverflow.com/a/63456129/2039339 answer.

To make the find_package(OpenCV REQUIRED) work correctly you will have to define the path to the OpenCV cmake files by setting the OpenCV_DIR by adding the following line to your CMakeList (replace with your exact location):

set(OpenCV_DIR "/home/{user}/anaconda3/pkgs/opencv-4.6.0-py39hd653453_2/lib/cmake/opencv4")

Then in your code you can include OpenCV headers

#include <opencv2/opencv.hpp>

Note: My pip installation of OpenCV however does not contain some dependencies like libQt* or libopenjp2 etc. so I still have to work on this to get it work :)

Khamyl
  • 398
  • 2
  • 12