A session of REPL / C++ with opencv

Load, display and manipulate images with opencv. Demonstrates how to load an external library and display advanced items.

In [1]:
#include "init.opencv.cpp"
// Then use it
cv::Mat lena = cv::imread("data/lena.jpg");
cv::resize(lena, lena, cv::Size(375, 183))
In [2]:
im::show(lena)
Out[2]:
In [4]:
[] { // // this is an immediately invoked lambda (IIL) : see the () at the end
cv::Mat blur;
cv::blur(lena, blur, cv::Size(15, 15));
return im::show(blur);
}() // () will call the lambda immediately
Out[4]:

How this is done

init.opencv.cpp will init opencv (include headers, load libs, and define im::show(const cv::Mat &)

#pragma cling add_library_path("/srv/conda/lib/")
#pragma cling add_include_path("   /srv/conda/include")
#pragma cling load("libopencv_core")
#pragma cling load("libopencv_imgcodecs")
#pragma cling load("libopencv_imgproc")

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "xtl/xbase64.hpp"
#include "nlohmann/json.hpp"

namespace im
{
    struct matshow
    {
        matshow(const cv::Mat& m) : _mat(m) {}
        cv::Mat _mat;
    };;

    matshow show(const cv::Mat& m) { matshow r(m); return r; }

    nlohmann::json mime_bundle_repr(const matshow& m)
    {
        std::vector<uchar> buf;
        bool success =  cv::imencode(".png", m._mat, buf);
        if (success) {
            auto bundle = nlohmann::json::object();
            std::string buf_as_str(buf.begin(), buf.end());
            bundle["image/jpeg"] = xtl::base64encode(buf_as_str);
            return bundle;
        }
        else
            return {};
    }
}

It is inspired by the page Displaying rich content on the xeus documentation site.

Note: As of now, the image display is a bit slow (see https://github.com/QuantStack/xeus-cling/issues/203)