如何使用python从OpenCV 3中的持久XML/YAML文件读取/写入矩阵?

whn*_*whn 6 python xml persistence opencv opencv3.0

我一直在尝试使用anaconda的当前cv2(我认为实际上是OpenCV 3.x)读取和写入矩阵到持久文件存储(例如XML ).我在网上查看了解决方案,人们参考了这样的事情:

object = cv2.cv.Load(file)
object = cv2.cv.Save(file)
Run Code Online (Sandbox Code Playgroud)

来源.这对当前的anaconda python不起作用cv2.人们提出像这样的例子的解决方案,但我很困惑为什么这个简单的功能需要这么多锅炉板代码,我不认为这是一个可接受的解决方案.我想要一些像旧解决方案一样简单的东西.

whn*_*whn 14

在我问这个问题之前,我知道如何解决这个问题,但我知道如何解决这个问题的唯一原因是因为我也在学习如何在C++中同时执行此操作.如何在opencv的最新更新中完成此操作在文档中根本没有说明.我无法在网上找到任何解决方案,所以希望那些不使用C++的人可以在python中理解如何做到这一点并付出很多努力.

这个最小的例子应该足以向您展示该过程的工作原理.实际上,opencv的当前python包装器看起来更像c ++版本,现在你cv2.FileStorage直接使用而不是cv2.cv.Savecv2.cv.Load.

python cv2.FileStorage现在是它自己的文件处理程序,就像在C++中一样.在c ++中,如果要使用FileStorage 写入文件,则可以执行以下操作:

cv::FileStorage opencv_file("test.xml", cv::FileStorage::WRITE);
cv::Mat file_matrix;
file_matrix = (cv::Mat_<int>(3, 3) << 1, 2, 3,
                                      3, 4, 6,
                                      7, 8, 9); 
opencv_file << "my_matrix" << file_matrix
opencv_file.release();
Run Code Online (Sandbox Code Playgroud)

阅读,您将执行以下操作:

cv::FileStorage opencv_file("test.xml", cv::FileStorage::READ);
cv::Mat file_matrix;
opencv_file["my_matrix"] >> file_matrix;
opencv_file.release();
Run Code Online (Sandbox Code Playgroud)

在python中,如果你想写,你必须做以下事情

#notice how its almost exactly the same, imagine cv2 is the namespace for cv 
#in C++, only difference is FILE_STORGE_WRITE is exposed directly in cv2
cv_file = cv2.FileStorage("test.xml", cv2.FILE_STORAGE_WRITE)
#creating a random matrix
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("write matrix\n", matrix)
# this corresponds to a key value pair, internally opencv takes your numpy 
# object and transforms it into a matrix just like you would do with << 
# in c++
cv_file.write("my_matrix", matrix)
# note you *release* you don't close() a FileStorage object
cv_file.release()
Run Code Online (Sandbox Code Playgroud)

如果你想阅读矩阵,那就更加做作了.

# just like before we specify an enum flag, but this time it is 
# FILE_STORAGE_READ
cv_file = cv2.FileStorage("test.xml", cv2.FILE_STORAGE_READ)
# for some reason __getattr__ doesn't work for FileStorage object in python
# however in the C++ documentation, getNode, which is also available, 
# does the same thing
#note we also have to specify the type to retrieve other wise we only get a 
# FileNode object back instead of a matrix
matrix = cv_file.getNode("my_matrix").mat()
print("read matrix\n", matrix)
cv_file.release()
Run Code Online (Sandbox Code Playgroud)

读写python示例的输出应该是:

write matrix
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

read matrix
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
Run Code Online (Sandbox Code Playgroud)

XML看起来像这样:

<?xml version="1.0"?>
<opencv_storage>
<my_matrix type_id="opencv-matrix">
  <rows>3</rows>
  <cols>3</cols>
  <dt>i</dt>
  <data>
    1 2 3 4 5 6 7 8 9</data></my_matrix>
</opencv_storage>
Run Code Online (Sandbox Code Playgroud)