Ask Your Question

Pass cv2.Mat (python) object to cv::Mat (c++) with SWIG

asked 2014-10-03 09:15:11 -0600

carlosb gravatar image

updated 2014-10-03 09:16:08 -0600

I am trying to pass from Python a cv2 Mat object to my SWIG wrapper for C++. My module in C++ is this:.

#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <memory>
#include <cmath>

#include "core.h"
#include "symbol_descriptor.h"
#include "symbol_matcher.h"

namespace cvc {

    class SymbolTracker: public  core::Tracker  {
            /* load configuration */
            void loadConfiguration();
            void initialization();

            SymbolTracker(std::vector<std::string> modelImageFiles
                ,std::string orbFile_=cvc::ORB_FILE
                ,std::string flannFile_=cvc::FLANN_FILE) ;
            core::ResultResponse process(cv::Mat & colorFrame, cv::Mat & grayFrame);




the SWIG file:

/* File : tracker.i */
%module symbol_tracker
%include "std_string.i"
%include "std_vector.i"

namespace std {
   %template(vectors) vector<std::string>;

#include "symbol_tracker.h"

/* Let's just grab the original header file here */
/*%include "core.h" */
%include "core.h"
%include "symbol_tracker.h"

And the python script to test the wrapper:

import symbol_tracker
import numpy as np
import cv2

img = cv2.imread('test_resources/model_image.bmp')

listModels = symbol_tracker.vectors()

tracker = symbol_tracker.SymbolTracker(listModels,symbol_tracker.ORB_FILE,symbol_tracker.FLANN_FILE)

grayImage = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
response = tracker.process(img,grayImage)

I get an error to use an incompatible argument:

Traceback (most recent call last):
  File "", line 17, in <module>
    response = tracker.process(img,grayImage)
TypeError: in method 'SymbolTracker_process', argument 2 of type 'cv::Mat &'

But I don't know how I could parse my grayImage and img argument in order to call correctly the function...

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2020-08-10 07:36:34 -0600

Swig does not convert the opencv datatypes from python to C++. For that, some interfacing/mapping has to be done. Opencv-SWIG library does this job for you and this instruction make things easy.

edit flag offensive delete link more

Question Tools


Asked: 2014-10-03 09:15:11 -0600

Seen: 2,298 times

Last updated: Oct 03 '14