Friday, December 20, 2019

Tip: Using matplotlib from Python in Visual C++

Recently when playing with OpenCV, I realized that I need to have a library that can display images with the scale that i can set. After some searching, I found that I can make use of the matplotlib library from Python in my C++ program. After further searching, I found that I can borrow the C++ library that call to the Python matplotlib library from the following GitHub Matplotlib

How the C++ library can make use of the Python matplotlib package is by using the Python compiled library (Python36.lib) and referencing the Python.h header file, which I got it from the Python installation path at C:\Program Files (x86)\Python3.6.3\libs. If the file you are an invalid lib file or dll file, most probably you will see the following error.
In order to get rid of this error, I built the application with 32-bit release version of python library.


I have to ensure that I have matplotlib installed for Python. Note that I have multiple versions of the Python installed in my PC and I need to install the matplotlib package just for Python3.6.3 because I am going to use that Python version in my C++ project. I used the following command to install the matplotlib package just for Python 3.6.3

C:\Program Files (x86)\Python3.6.3>python -m pip install matplotlib.

Basically I CD the Python installation path so that when i call the Python command it will call to the 3.6.3 version, as my default Python installation at that time was 3.7.3, which is not what i want to use in my C++ project.

Note: If you are using python.exe, that means the numpy and matplotlib packages need to be compatible with the "Release" version. If you are using python_d.exe then you need to ensure numpy and matplotlib is compatible with the "Debug" version. For debug version you can use C:\Program Files (x86)\Python3.6.3>python_d.exe -m pip install matplotlib to do correct package installation. Typical error one will get when the version is not compatible is ImportError: cannot import name 'multiarray'
A good guideline for using debug version of the Python with release version of matplotlib from within Visual C++ Numpy issue

The full source code for the release can be retrieved from GitHub https://github.com/leonwooster/matplotlib