0

I am trying to convert a NumPy array to an OpenCV matrix object so that it can be passed to an OpenCV wrapper written in C++.

For context, I am using OpenCV 3.4.8 and below is what my python script looks like

import sys
sys.path.append('/usr/local/lib/python3.8/site-packages')

import cv2
import numpy as np
import opencv_wrapper2


# Load two images
img1 = cv2.imread('images/image1.jpg')
img2 = cv2.imread('images/image2.jpg')
# Convert to uint8 datatype
img1 = img1.astype(np.uint8)
img2 = img2.astype(np.uint8)
# convert the numpy ndarray to BGR format
img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2BGR)
img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2BGR)

h1, w1, c1 = img1.shape
h2, w2, c2 = img2.shape

# Convert the NumPy array to an OpenCV matrix object
cv_mat1 = cv2.fromarray(img1)
cv_mat2 = cv2.fromarray(img2)

repeatability = opencv_wrapper2.calculateRepeatability(img1, h1, w1, c1, img2, h2, w2, c2)

However, I keep getting this error

AttributeError: module 'cv2.cv2' has no attribute 'fromarray'

I tried using the opencv-python function 'cv2.cvtColor()' to hopefully convert it to a cv::Mat object but it did not work.

I tried converting the C++ function receiving the arguments to void* datatype but it also did not work

#define OPENCV_TRAITS_ENABLE_DEPRECATED
#include "./pybind11/include/pybind11/pybind11.h"
#include "./pybind11/include/pybind11/numpy.h"
#include "./pybind11/include/pybind11/stl.h"
#include <opencv2/opencv.hpp>
#include <vector>
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/core/mat.hpp>
#include <opencv2/core.hpp>
#include <iostream>
#include <typeinfo>

using namespace std;
using namespace cv;
namespace py = pybind11;


float calculateRepeatability(void* data1, int height1, int width1, int channels1, void* data2, int height2, int width2, int channels2) //Remove h1to2
{
 ...
}

PYBIND11_MODULE(opencv_wrapper, m) {
    m.def("calculateRepeatability", &calculateRepeatability, "Compute the repeatability of a feature detector with threshold 0.4");
}

I keep getting the same error

TypeError: calculateRepeatability(): incompatible function arguments. The following argument types are supported:
    1. (arg0: capsule, arg1: int, arg2: int, arg3: int, arg4: capsule, arg5: int, arg6: int, arg7: int) -> float

Invoked with: array([[[ 4,  4,  2],
        [ 3,  3,  1],
        [ 2,  2,  0],
        ...,

Please help

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • [Does this answer your question?](https://stackoverflow.com/questions/29758662/c-conversion-from-numpy-array-to-mat-opencv) – DrBwts Apr 25 '23 at 09:28
  • I'm having errors with the `pbcvt` repo which is included in the post with `boost` , lots of errors related to older version of OpenCV. It assumes Python 2.x and OpenCV 2.x both of which are no longer maintained. I was wondering if there is a simpler solution with pybind11. – dev_4a_living May 02 '23 at 10:27

0 Answers0