簡體   English   中英

如何使用python從OpenCV 3中的持久XML / YAML文件讀取/寫入矩陣?

[英]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)

來源 這對當前的anaconda python cv2 人們提出像這樣的例子的解決方案,但我很困惑為什么這個簡單的功能需要這么多鍋爐板代碼,我不認為這是一個可接受的解決方案。 我想要一些像舊解決方案一樣簡單的東西。

在我問這個問題之前,我知道如何解決這個問題,但我知道如何解決這個問題的唯一原因是因為我也在學習如何在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();

閱讀,您將執行以下操作:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM