如何使用 python 从 OpenCV 3 中的持久性 XML/YAML 文件 read/write 矩阵?

How to read/write a matrix from a persistent XML/YAML file in OpenCV 3 with python?

我一直在尝试使用 anaconda 的当前 cv2(我相信它实际上是 OpenCV 3.x)将矩阵读写到持久文件存储(例如 XML)。我在网上查看了解决方案,人们参考了这样的做法:

object = cv2.cv.Load(file)
object = cv2.cv.Save(file)

source. This does not work on the current anaconda python cv2. People propose solutions like this yaml example,但我很困惑为什么这个简单的功能需要这么多样板代码,我认为这不是一个可接受的解决方案。我想要像旧解决方案一样简单的东西。

在我问这个之前我就知道如何解决这个问题,但我知道如何解决这个问题的唯一原因是因为我也在学习如何在 C++ 中同时执行此操作。这是如何在最近更新的 opencv 中完成的 not stated at all in the documentation。我在网上找不到任何地方可以解决这个问题,所以希望那些不使用 C++ 的人可以在 python 中轻松理解如何做到这一点。

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

python cv2.FileStorage 现在是它自己的文件处理程序,就像它在 C++ 中一样。在 c++ 中,如果你想 write 到带有 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();

阅读,您需要执行以下操作:

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

在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()

如果你想 读取 矩阵,它有点做作。

# 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()

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

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

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

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>