I am trying to open images in C++ using OpenCV and to send a pointer (image.data) to Python where I convert image.data to a numpy array using Numpy's frombuffer method. In some cases the sending works perfectly and in case of some images I have a problem. After converting the image to numpy array, the image in Python has a different dimension( for example 19x19) then the original image in C++ ( for example 100x100). The problem appears every time in case of the same images. I don't understand why I lost data only in some cases and in other cases it works perfectly.
The code in C++
#include <stdio.h>
#include <Python.h>
#include <opencv2/opencv.hpp>
int main()
{
CPyInstance hInstance;
CPyObject pName = PyUnicode_FromString("loadTensorflow");
CPyObject pModule = PyImport_Import(pName);
if (pModule)
{
CPyObject pFunc1 = PyObject_GetAttrString(pModule, "loadModel");
CPyObject pFunc2 = PyObject_GetAttrString(pModule, "makePredict");
if (pFunc1 && PyCallable_Check(pFunc1) && pFunc2 && PyCallable_Check(pFunc2))
{
CPyObject pValue1 = PyObject_CallObject(pFunc1, NULL);
//src is the path
Mat image = imread(src, IMREAD_GRAYSCALE);
PyObject* arglist = Py_BuildValue("(iiy)", image.rows, image.cols, image.data);
CPyObject pValue2 = PyObject_CallObject(pFunc2, arglist);
if (pValue2!=NULL)
Py_DECREF(pValue2);
else
PyErr_Print();
double predict_val = PyFloat_AsDouble(pValue2);
printf("Returned value by predict() = %lf\n", predict_val);
}
else
{
printf("ERROR: function\n");
}
}
else
{
printf_s("ERROR: Module not imported\n");
PyErr_Print();
}
return 0;
}
The code in Python
import numpy as np
def makePredict(height, width, imageData):
#print('Here I am')
image = np.frombuffer(imageData,
dtype='u1',
count=int(height)*int(width)).reshape((int(height), int(width)))
#print('This message doesn't appears!')
#some processing on image
#return a value
The makePredict method is called successfully but when I try to call np.frombuffer method with an image that doesn't works well I got an error: ValueError: buffer is smaller than requested size. I think that this error appears because I lost data when I send from C++ to Python. In case of other images the method works well, without error. I try the method with images from a dataset: every image is grayscale and has a dimension of 100x100. I tried to print height, width and the value of each pixel in C++ and there's no problem.
Please let me know if anybody has any idea. Thank you!