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

5us2dqdw  于 2023-01-16  发布在  Python
关注(0)|答案(1)|浏览(405)

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

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

Source。这在当前的Anaconda Python cv2上不起作用。人们提出了类似this YAML example的解决方案,但我很困惑为什么这个简单的功能需要这么多的样板代码,我不认为这是一个可接受的解决方案。我想要像旧解决方案一样简单的解决方案。

3phpmpom

3phpmpom1#

opencv的最新更新是not stated at all in the documentation
这个最小的例子应该足以向你展示这个过程是如何工作的。实际上,当前的OpenCV Python Package 器看起来更像C版本,而且你现在直接使用cv2.FileStorage,而不是cv2.cv.Savecv2.cv.Load
Python cv2.FileStorage现在是它自己的文件处理器,就像它在C
中一样。在C++中,如果你想用FileStorage write 到一个文件,你需要做以下事情:

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 it’s almost exactly the same. Imagine cv2 is the namespace for cv.
# In C++, the 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, and 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, otherwise 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>

相关问题