英文:
Is there any easy way to save cv::mat as npy file in C++?
问题
我正在修改一个系统的输出,以匹配另一个系统的输入。第一个系统是用C++编写的,第二个系统是用Python编写的。第二个系统需要npy文件作为输入,所以我必须在第一个系统中将cv::Mat保存为npy文件。但是当我在互联网上进行了一些调查时,我发现可能需要使用boost::python来实现这个目标。是否有一种简单的方法来将cv::Mat保存为npy文件,因为我不想在我的机器上安装Python。
英文:
I'm modifying the output of one system to match the input of another system. The first system was written in C++ and second system was written in python. The second system requires npy file as input, so I have to save cv:Mat as npy file in the first system. But when I did some investigation on Internet, I found I may have to use boost::python to do so. Is there any easy way to save cv:mat to npy file, because I don't want to install python on my machine.
答案1
得分: 1
可以通过相对简单的方式与numpy的C绑定进行接口。你需要阅读numpy文档上关于“扩展numpy”部分的详细说明。
当然,如果要编写使用numpy代码来写入二进制文件的C++代码,你需要安装numpy的开发头文件。这可能会导致numpy和Python的安装。
不过,老实说,numpy.fromfile
可以很好地加载原始数据文件,其中只包含与你的openCV C++程序中的内存中的数字相同的数据。因此,如果不需要在这些程序部分之间传输复杂的数据结构,只需要处理数字数组,那会更容易。
另一个选择是保存为hdf5格式;numpy可以读取这种结构化的文件格式,而且有用于C和C++的库可以写入它。
最常见的方法是将你的C++代码用作库,并构建一个包装器,以便你可以使用numpy数据类型从Python中调用C++代码,而包装器会自动执行numpy数组到C++类型的转换以及相反的操作。我认为如今最流行的包装器是pybind11,它可以很好地与numpy ndarray进行交互。
英文:
Yes you can interface with numpy's C bindings in a relatively straight forward way. You'll want to do read the rather well-written numpy documentation on "extending numpy" with native code.
If course, to write C++ code that uses numpy code to write bumpy files, to will need to install numpy development headers. Which will probably lead to the installation of numpy and thus python anyways.
However, honestly, numpy.fromfile
can load raw data files, containing nothing but the numbers as they were in the memory of your openCV C++ program just fine. So, if you don't need to transport any complicated structure between these program parts, but just arrays of numbers, that's easier.
Another option is to save hdf5; numpy can read that structured file format, and there's libraries for C and C++ to write it.
The most common way is to just use your c++ code as a library, and build a bit of wrapper, so you can call your C++ code from python with numpy data types, and the wrapping paper magically does the conversion of numpy arrays to C++ types and back. I think these days, pybind11 is the most popular wrapper, and it does wrap to and from numpy ndarray rather well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论