mirror of
https://github.com/opencv/opencv.git
synced 2025-06-07 01:13:28 +08:00
Merge pull request #26260 from sturkmen72:upd_doc_4_x
Update Documentation #26260 ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [ ] There is a reference to the original bug report and related work - [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [ ] The feature is well documented and sample code can be built with the project CMake
This commit is contained in:
parent
cefde84a76
commit
e72efd0d32
@ -1,4 +1,4 @@
|
||||
File Input and Output using XML and YAML files {#tutorial_file_input_output_with_xml_yml}
|
||||
File Input and Output using XML / YAML / JSON files {#tutorial_file_input_output_with_xml_yml}
|
||||
==============================================
|
||||
|
||||
@tableofcontents
|
||||
@ -14,12 +14,12 @@ File Input and Output using XML and YAML files {#tutorial_file_input_output_with
|
||||
Goal
|
||||
----
|
||||
|
||||
You'll find answers for the following questions:
|
||||
You'll find answers to the following questions:
|
||||
|
||||
- How to print and read text entries to a file and OpenCV using YAML or XML files?
|
||||
- How to do the same for OpenCV data structures?
|
||||
- How to do this for your data structures?
|
||||
- Usage of OpenCV data structures such as @ref cv::FileStorage , @ref cv::FileNode or @ref
|
||||
- How do you print and read text entries to a file in OpenCV using YAML, XML, or JSON files?
|
||||
- How can you perform the same operations for OpenCV data structures?
|
||||
- How can this be done for your custom data structures?
|
||||
- How do you use OpenCV data structures, such as @ref cv::FileStorage , @ref cv::FileNode or @ref
|
||||
cv::FileNodeIterator .
|
||||
|
||||
Source code
|
||||
@ -49,14 +49,14 @@ Here's a sample code of how to achieve all the stuff enumerated at the goal list
|
||||
Explanation
|
||||
-----------
|
||||
|
||||
Here we talk only about XML and YAML file inputs. Your output (and its respective input) file may
|
||||
Here we talk only about XML, YAML and JSON file inputs. Your output (and its respective input) file may
|
||||
have only one of these extensions and the structure coming from this. They are two kinds of data
|
||||
structures you may serialize: *mappings* (like the STL map and the Python dictionary) and *element sequence* (like the STL
|
||||
vector). The difference between these is that in a map every element has a unique name through what
|
||||
you may access it. For sequences you need to go through them to query a specific item.
|
||||
|
||||
-# **XML/YAML File Open and Close.** Before you write any content to such file you need to open it
|
||||
and at the end to close it. The XML/YAML data structure in OpenCV is @ref cv::FileStorage . To
|
||||
-# **XML/YAML/JSON File Open and Close.** Before you write any content to such file you need to open it
|
||||
and at the end to close it. The XML/YAML/JSON data structure in OpenCV is @ref cv::FileStorage . To
|
||||
specify that this structure to which file binds on your hard drive you can use either its
|
||||
constructor or the *open()* function of this:
|
||||
@add_toggle_cpp
|
||||
|
@ -14,6 +14,9 @@ libraries. The following modules are available:
|
||||
- @ref imgproc (**imgproc**) - an image processing module that includes linear and non-linear image filtering,
|
||||
geometrical image transformations (resize, affine and perspective warping, generic table-based
|
||||
remapping), color space conversion, histograms, and so on.
|
||||
- @ref imgcodecs (**imgcodecs**) - includes functions for reading and writing image files in various formats.
|
||||
- @ref videoio (**videoio**) - an easy-to-use interface to video capturing and video codecs.
|
||||
- @ref highgui (**highgui**) - an easy-to-use interface to simple UI capabilities.
|
||||
- @ref video (**video**) - a video analysis module that includes motion estimation, background subtraction,
|
||||
and object tracking algorithms.
|
||||
- @ref calib3d (**calib3d**) - basic multiple-view geometry algorithms, single and stereo camera calibration,
|
||||
@ -21,8 +24,11 @@ libraries. The following modules are available:
|
||||
- @ref features2d (**features2d**) - salient feature detectors, descriptors, and descriptor matchers.
|
||||
- @ref objdetect (**objdetect**) - detection of objects and instances of the predefined classes (for example,
|
||||
faces, eyes, mugs, people, cars, and so on).
|
||||
- @ref highgui (**highgui**) - an easy-to-use interface to simple UI capabilities.
|
||||
- @ref videoio (**videoio**) - an easy-to-use interface to video capturing and video codecs.
|
||||
- @ref dnn (**dnn**) - Deep Neural Network module.
|
||||
- @ref ml (**ml**) - The Machine Learning module includes a set of classes and functions for statistical classification,
|
||||
regression, and clustering of data.
|
||||
- @ref photo (**photo**) - advanced photo processing techniques like denoising, inpainting.
|
||||
- @ref stitching (**stitching**) - functions for image stitching and panorama creation.
|
||||
- ... some other helper modules, such as FLANN and Google test wrappers, Python bindings, and
|
||||
others.
|
||||
|
||||
|
@ -60,11 +60,16 @@
|
||||
|
||||
/**
|
||||
@defgroup core Core functionality
|
||||
|
||||
The Core module is the backbone of OpenCV, offering fundamental data structures, matrix operations,
|
||||
and utility functions that other modules depend on. It’s essential for handling image data,
|
||||
performing mathematical computations, and managing memory efficiently within the OpenCV ecosystem.
|
||||
|
||||
@{
|
||||
@defgroup core_basic Basic structures
|
||||
@defgroup core_array Operations on arrays
|
||||
@defgroup core_async Asynchronous API
|
||||
@defgroup core_xml XML/YAML Persistence
|
||||
@defgroup core_xml XML/YAML/JSON Persistence
|
||||
@defgroup core_cluster Clustering
|
||||
@defgroup core_utils Utility and system functions and macros
|
||||
@{
|
||||
@ -76,7 +81,6 @@
|
||||
@defgroup core_utils_samples Utility functions for OpenCV samples
|
||||
@}
|
||||
@defgroup core_opengl OpenGL interoperability
|
||||
@defgroup core_ipp Intel IPP Asynchronous C/C++ Converters
|
||||
@defgroup core_optim Optimization Algorithms
|
||||
@defgroup core_directx DirectX interoperability
|
||||
@defgroup core_eigen Eigen support
|
||||
@ -96,6 +100,7 @@
|
||||
@{
|
||||
@defgroup core_parallel_backend Parallel backends API
|
||||
@}
|
||||
@defgroup core_quaternion Quaternion
|
||||
@}
|
||||
*/
|
||||
|
||||
@ -163,7 +168,7 @@ enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independe
|
||||
|
||||
//! @} core_utils
|
||||
|
||||
//! @addtogroup core
|
||||
//! @addtogroup core_array
|
||||
//! @{
|
||||
|
||||
//! Covariation flags
|
||||
@ -202,27 +207,6 @@ enum CovarFlags {
|
||||
COVAR_COLS = 16
|
||||
};
|
||||
|
||||
//! @addtogroup core_cluster
|
||||
//! @{
|
||||
|
||||
//! k-Means flags
|
||||
enum KmeansFlags {
|
||||
/** Select random initial centers in each attempt.*/
|
||||
KMEANS_RANDOM_CENTERS = 0,
|
||||
/** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/
|
||||
KMEANS_PP_CENTERS = 2,
|
||||
/** During the first (and possibly the only) attempt, use the
|
||||
user-supplied labels instead of computing them from the initial centers. For the second and
|
||||
further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag
|
||||
to specify the exact method.*/
|
||||
KMEANS_USE_INITIAL_LABELS = 1
|
||||
};
|
||||
|
||||
//! @} core_cluster
|
||||
|
||||
//! @addtogroup core_array
|
||||
//! @{
|
||||
|
||||
enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix.
|
||||
REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix.
|
||||
REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix.
|
||||
@ -230,19 +214,12 @@ enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/column
|
||||
REDUCE_SUM2 = 4 //!< the output is the sum of all squared rows/columns of the matrix.
|
||||
};
|
||||
|
||||
//! @} core_array
|
||||
|
||||
/** @brief Swaps two matrices
|
||||
*/
|
||||
CV_EXPORTS void swap(Mat& a, Mat& b);
|
||||
/** @overload */
|
||||
CV_EXPORTS void swap( UMat& a, UMat& b );
|
||||
|
||||
//! @} core
|
||||
|
||||
//! @addtogroup core_array
|
||||
//! @{
|
||||
|
||||
/** @brief Computes the source location of an extrapolated pixel.
|
||||
|
||||
The function computes and returns the coordinate of a donor pixel corresponding to the specified
|
||||
@ -557,6 +534,10 @@ The format of half precision floating point is defined in IEEE 754-2008.
|
||||
*/
|
||||
CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst);
|
||||
|
||||
/** @example samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp
|
||||
Check @ref tutorial_how_to_scan_images "the corresponding tutorial" for more details
|
||||
*/
|
||||
|
||||
/** @brief Performs a look-up table transform of an array.
|
||||
|
||||
The function LUT fills the output array with values from the look-up table. Indices of the entries
|
||||
@ -3085,8 +3066,21 @@ private:
|
||||
//! @addtogroup core_cluster
|
||||
//! @{
|
||||
|
||||
//! k-means flags
|
||||
enum KmeansFlags {
|
||||
/** Select random initial centers in each attempt.*/
|
||||
KMEANS_RANDOM_CENTERS = 0,
|
||||
/** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/
|
||||
KMEANS_PP_CENTERS = 2,
|
||||
/** During the first (and possibly the only) attempt, use the
|
||||
user-supplied labels instead of computing them from the initial centers. For the second and
|
||||
further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag
|
||||
to specify the exact method.*/
|
||||
KMEANS_USE_INITIAL_LABELS = 1
|
||||
};
|
||||
|
||||
/** @example samples/cpp/kmeans.cpp
|
||||
An example on K-means clustering
|
||||
An example on k-means clustering
|
||||
*/
|
||||
|
||||
/** @brief Finds centers of clusters and groups input samples around the clusters.
|
||||
@ -3096,7 +3090,7 @@ and groups the input samples around the clusters. As an output, \f$\texttt{bestL
|
||||
0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix.
|
||||
|
||||
@note
|
||||
- (Python) An example on K-means clustering can be found at
|
||||
- (Python) An example on k-means clustering can be found at
|
||||
opencv_source_code/samples/python/kmeans.py
|
||||
@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed.
|
||||
Examples of this array can be:
|
||||
|
@ -51,7 +51,7 @@
|
||||
namespace cv
|
||||
{
|
||||
|
||||
//! @addtogroup core
|
||||
//! @addtogroup core_eigen
|
||||
//! @{
|
||||
|
||||
/** @brief Affine transform
|
||||
|
@ -288,28 +288,28 @@ enum BorderTypes {
|
||||
By default the function prints information about the error to stderr,
|
||||
then it either stops if setBreakOnError() had been called before or raises the exception.
|
||||
It is possible to alternate error processing by using redirectError().
|
||||
@param _code - error code (Error::Code)
|
||||
@param _err - error description
|
||||
@param _func - function name. Available only when the compiler supports getting it
|
||||
@param _file - source file name where the error has occurred
|
||||
@param _line - line number in the source file where the error has occurred
|
||||
@param code - error code (Error::Code)
|
||||
@param err - error description
|
||||
@param func - function name. Available only when the compiler supports getting it
|
||||
@param file - source file name where the error has occurred
|
||||
@param line - line number in the source file where the error has occurred
|
||||
@see CV_Error, CV_Error_, CV_Assert, CV_DbgAssert
|
||||
*/
|
||||
CV_EXPORTS CV_NORETURN void error(int _code, const String& _err, const char* _func, const char* _file, int _line);
|
||||
CV_EXPORTS CV_NORETURN void error(int code, const String& err, const char* func, const char* file, int line);
|
||||
|
||||
/*! @brief Signals an error and terminate application.
|
||||
|
||||
By default the function prints information about the error to stderr, then it terminates application
|
||||
with std::terminate. The function is designed for invariants check in functions and methods with
|
||||
noexcept attribute.
|
||||
@param _code - error code (Error::Code)
|
||||
@param _err - error description
|
||||
@param _func - function name. Available only when the compiler supports getting it
|
||||
@param _file - source file name where the error has occurred
|
||||
@param _line - line number in the source file where the error has occurred
|
||||
@param code - error code (Error::Code)
|
||||
@param err - error description
|
||||
@param func - function name. Available only when the compiler supports getting it
|
||||
@param file - source file name where the error has occurred
|
||||
@param line - line number in the source file where the error has occurred
|
||||
@see CV_AssertTerminate
|
||||
*/
|
||||
CV_EXPORTS CV_NORETURN void terminate(int _code, const String& _err, const char* _func, const char* _file, int _line) CV_NOEXCEPT;
|
||||
CV_EXPORTS CV_NORETURN void terminate(int code, const String& err, const char* func, const char* file, int line) CV_NOEXCEPT;
|
||||
|
||||
|
||||
#ifdef CV_STATIC_ANALYSIS
|
||||
|
@ -15,7 +15,7 @@
|
||||
namespace cv
|
||||
{
|
||||
|
||||
//! @addtogroup core
|
||||
//! @addtogroup core_opencl
|
||||
//! @{
|
||||
|
||||
class BufferPoolController
|
||||
|
@ -30,7 +30,7 @@
|
||||
#include <opencv2/core/affine.hpp>
|
||||
|
||||
namespace cv{
|
||||
//! @addtogroup core
|
||||
//! @addtogroup core_quaternion
|
||||
//! @{
|
||||
|
||||
template <typename _Tp> class DualQuat;
|
||||
|
@ -446,6 +446,22 @@ typedef OutputArray OutputArrayOfArrays;
|
||||
typedef const _InputOutputArray& InputOutputArray;
|
||||
typedef InputOutputArray InputOutputArrayOfArrays;
|
||||
|
||||
/** @brief Returns an empty InputArray or OutputArray.
|
||||
|
||||
This function is used to provide an "empty" or "null" array when certain functions
|
||||
take optional input or output arrays that you don't want to provide.
|
||||
|
||||
Many OpenCV functions accept optional arguments as `cv::InputArray` or `cv::OutputArray`.
|
||||
When you don't want to pass any data for these optional parameters, you can use `cv::noArray()`
|
||||
to indicate that you are omitting them.
|
||||
|
||||
@return An empty `cv::InputArray` or `cv::OutputArray` that can be used as a placeholder.
|
||||
|
||||
@note This is often used when a function has optional arrays, and you do not want to
|
||||
provide a specific input or output array.
|
||||
|
||||
@see cv::InputArray, cv::OutputArray
|
||||
*/
|
||||
CV_EXPORTS InputOutputArray noArray();
|
||||
|
||||
/////////////////////////////////// MatAllocator //////////////////////////////////////
|
||||
|
@ -508,7 +508,7 @@ The generic function partition implements an \f$O(N^2)\f$ algorithm for splittin
|
||||
into one or more equivalency classes, as described in
|
||||
<http://en.wikipedia.org/wiki/Disjoint-set_data_structure> . The function returns the number of
|
||||
equivalency classes.
|
||||
@param _vec Set of elements stored as a vector.
|
||||
@param vec Set of elements stored as a vector.
|
||||
@param labels Output vector of labels. It contains as many elements as vec. Each label labels[i] is
|
||||
a 0-based cluster index of `vec[i]`.
|
||||
@param predicate Equivalence predicate (pointer to a boolean function of two arguments or an
|
||||
@ -518,11 +518,11 @@ may or may not be in the same class.
|
||||
@ingroup core_cluster
|
||||
*/
|
||||
template<typename _Tp, class _EqPredicate> int
|
||||
partition( const std::vector<_Tp>& _vec, std::vector<int>& labels,
|
||||
partition( const std::vector<_Tp>& vec, std::vector<int>& labels,
|
||||
_EqPredicate predicate=_EqPredicate())
|
||||
{
|
||||
int i, j, N = (int)_vec.size();
|
||||
const _Tp* vec = &_vec[0];
|
||||
int i, j, N = (int)vec.size();
|
||||
const _Tp* _vec = &vec[0];
|
||||
|
||||
const int PARENT=0;
|
||||
const int RANK=1;
|
||||
@ -548,7 +548,7 @@ partition( const std::vector<_Tp>& _vec, std::vector<int>& labels,
|
||||
|
||||
for( j = 0; j < N; j++ )
|
||||
{
|
||||
if( i == j || !predicate(vec[i], vec[j]))
|
||||
if( i == j || !predicate(_vec[i], _vec[j]))
|
||||
continue;
|
||||
int root2 = j;
|
||||
|
||||
|
@ -53,50 +53,6 @@
|
||||
# error persistence.hpp header must be compiled as C++
|
||||
#endif
|
||||
|
||||
//! @addtogroup core_c
|
||||
//! @{
|
||||
|
||||
/** @brief "black box" representation of the file storage associated with a file on disk.
|
||||
|
||||
Several functions that are described below take CvFileStorage\* as inputs and allow the user to
|
||||
save or to load hierarchical collections that consist of scalar values, standard CXCore objects
|
||||
(such as matrices, sequences, graphs), and user-defined objects.
|
||||
|
||||
OpenCV can read and write data in XML (<http://www.w3c.org/XML>), YAML (<http://www.yaml.org>) or
|
||||
JSON (<http://www.json.org/>) formats. Below is an example of 3x3 floating-point identity matrix A,
|
||||
stored in XML and YAML files
|
||||
using CXCore functions:
|
||||
XML:
|
||||
@code{.xml}
|
||||
<?xml version="1.0">
|
||||
<opencv_storage>
|
||||
<A type_id="opencv-matrix">
|
||||
<rows>3</rows>
|
||||
<cols>3</cols>
|
||||
<dt>f</dt>
|
||||
<data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
|
||||
</A>
|
||||
</opencv_storage>
|
||||
@endcode
|
||||
YAML:
|
||||
@code{.yaml}
|
||||
%YAML:1.0
|
||||
A: !!opencv-matrix
|
||||
rows: 3
|
||||
cols: 3
|
||||
dt: f
|
||||
data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
|
||||
@endcode
|
||||
As it can be seen from the examples, XML uses nested tags to represent hierarchy, while YAML uses
|
||||
indentation for that purpose (similar to the Python programming language).
|
||||
|
||||
The same functions can read and write data in both formats; the particular format is determined by
|
||||
the extension of the opened file, ".xml" for XML files, ".yml" or ".yaml" for YAML and ".json" for
|
||||
JSON.
|
||||
*/
|
||||
|
||||
//! @} core_c
|
||||
|
||||
#include "opencv2/core/types.hpp"
|
||||
#include "opencv2/core/mat.hpp"
|
||||
|
||||
@ -283,13 +239,14 @@ element is a structure of 2 integers, followed by a single-precision floating-po
|
||||
equivalent notations of the above specification are `iif`, `2i1f` and so forth. Other examples: `u`
|
||||
means that the array consists of bytes, and `2d` means the array consists of pairs of doubles.
|
||||
|
||||
@see @ref samples/cpp/filestorage.cpp
|
||||
@see @ref samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp
|
||||
*/
|
||||
|
||||
//! @{
|
||||
|
||||
/** @example samples/cpp/filestorage.cpp
|
||||
/** @example samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp
|
||||
A complete example using the FileStorage interface
|
||||
Check @ref tutorial_file_input_output_with_xml_yml "the corresponding tutorial" for more details
|
||||
*/
|
||||
|
||||
////////////////////////// XML & YAML I/O //////////////////////////
|
||||
@ -322,10 +279,10 @@ public:
|
||||
};
|
||||
enum State
|
||||
{
|
||||
UNDEFINED = 0,
|
||||
VALUE_EXPECTED = 1,
|
||||
NAME_EXPECTED = 2,
|
||||
INSIDE_MAP = 4
|
||||
UNDEFINED = 0, //!< Initial or uninitialized state.
|
||||
VALUE_EXPECTED = 1, //!< Expecting a value in the current position.
|
||||
NAME_EXPECTED = 2, //!< Expecting a key/name in the current position.
|
||||
INSIDE_MAP = 4 //!< Indicates being inside a map (a set of key-value pairs).
|
||||
};
|
||||
|
||||
/** @brief The constructors.
|
||||
|
@ -31,7 +31,7 @@
|
||||
#include <iostream>
|
||||
namespace cv
|
||||
{
|
||||
//! @addtogroup core
|
||||
//! @addtogroup core_quaternion
|
||||
//! @{
|
||||
|
||||
//! Unit quaternion flag
|
||||
|
@ -176,7 +176,38 @@ extern "C" typedef int (*ErrorCallback)( int status, const char* func_name,
|
||||
*/
|
||||
CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0);
|
||||
|
||||
/** @brief Generates a unique temporary file name.
|
||||
|
||||
This function generates a full, unique file path for a temporary file,
|
||||
which can be used to create temporary files for various purposes.
|
||||
|
||||
@param suffix (optional) The desired file extension or suffix for the temporary file (e.g., ".png", ".txt").
|
||||
If no suffix is provided (suffix = 0), the file will not have a specific extension.
|
||||
|
||||
@return cv::String A full unique path for the temporary file.
|
||||
|
||||
@note
|
||||
- The function does not create the file, it only generates the name.
|
||||
- The file name is unique for the system session.
|
||||
- Works cross-platform (Windows, Linux, macOS).
|
||||
*/
|
||||
CV_EXPORTS String tempfile( const char* suffix = 0);
|
||||
|
||||
/** @brief Searches for files matching the specified pattern in a directory.
|
||||
|
||||
This function searches for files that match a given pattern (e.g., `*.jpg`)
|
||||
in the specified directory. The search can be limited to the directory itself
|
||||
or be recursive, including subdirectories.
|
||||
|
||||
@param pattern The file search pattern, which can include wildcards like `*`
|
||||
(for matching multiple characters) or `?` (for matching a single character).
|
||||
|
||||
@param result Output vector where the file paths matching the search
|
||||
pattern will be stored.
|
||||
@param recursive (optional) Boolean flag indicating whether to search
|
||||
subdirectories recursively. If true, the search will include all subdirectories.
|
||||
The default value is `false`.
|
||||
*/
|
||||
CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
|
||||
|
||||
/** @brief OpenCV will try to set the number of threads for subsequent parallel regions.
|
||||
|
@ -48,7 +48,7 @@
|
||||
/**
|
||||
@defgroup imgproc Image Processing
|
||||
|
||||
This module includes image-processing functions.
|
||||
This module offers a comprehensive suite of image processing functions, enabling tasks such as those listed above.
|
||||
|
||||
@{
|
||||
@defgroup imgproc_filter Image Filtering
|
||||
|
@ -1,193 +0,0 @@
|
||||
/*
|
||||
* filestorage_sample demonstrate the usage of the opencv serialization functionality
|
||||
*/
|
||||
|
||||
#include "opencv2/core.hpp"
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
using std::string;
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
using std::cerr;
|
||||
using std::ostream;
|
||||
using namespace cv;
|
||||
|
||||
static void help(char** av)
|
||||
{
|
||||
cout << "\nfilestorage_sample demonstrate the usage of the opencv serialization functionality.\n"
|
||||
<< "usage:\n"
|
||||
<< av[0] << " outputfile.yml.gz\n"
|
||||
<< "\n outputfile above can have many different extensions, see below."
|
||||
<< "\nThis program demonstrates the use of FileStorage for serialization, that is in use << and >> in OpenCV\n"
|
||||
<< "For example, how to create a class and have it serialize, but also how to use it to read and write matrices.\n"
|
||||
<< "FileStorage allows you to serialize to various formats specified by the file end type."
|
||||
<< "\nYou should try using different file extensions.(e.g. yaml yml xml xml.gz yaml.gz etc...)\n" << endl;
|
||||
}
|
||||
|
||||
struct MyData
|
||||
{
|
||||
MyData() :
|
||||
A(0), X(0), id()
|
||||
{
|
||||
}
|
||||
explicit MyData(int) :
|
||||
A(97), X(CV_PI), id("mydata1234")
|
||||
{
|
||||
}
|
||||
int A;
|
||||
double X;
|
||||
string id;
|
||||
void write(FileStorage& fs) const //Write serialization for this class
|
||||
{
|
||||
fs << "{" << "A" << A << "X" << X << "id" << id << "}";
|
||||
}
|
||||
void read(const FileNode& node) //Read serialization for this class
|
||||
{
|
||||
|
||||
A = (int)node["A"];
|
||||
X = (double)node["X"];
|
||||
id = (string)node["id"];
|
||||
}
|
||||
};
|
||||
|
||||
//These write and read functions must exist as per the inline functions in operations.hpp
|
||||
static void write(FileStorage& fs, const std::string&, const MyData& x){
|
||||
x.write(fs);
|
||||
}
|
||||
static void read(const FileNode& node, MyData& x, const MyData& default_value = MyData()){
|
||||
if(node.empty())
|
||||
x = default_value;
|
||||
else
|
||||
x.read(node);
|
||||
}
|
||||
|
||||
static ostream& operator<<(ostream& out, const MyData& m){
|
||||
out << "{ id = " << m.id << ", ";
|
||||
out << "X = " << m.X << ", ";
|
||||
out << "A = " << m.A << "}";
|
||||
return out;
|
||||
}
|
||||
int main(int ac, char** av)
|
||||
{
|
||||
cv::CommandLineParser parser(ac, av,
|
||||
"{@input||}{help h ||}"
|
||||
);
|
||||
if (parser.has("help"))
|
||||
{
|
||||
help(av);
|
||||
return 0;
|
||||
}
|
||||
string filename = parser.get<string>("@input");
|
||||
if (filename.empty())
|
||||
{
|
||||
help(av);
|
||||
return 1;
|
||||
}
|
||||
|
||||
//write
|
||||
{
|
||||
FileStorage fs(filename, FileStorage::WRITE);
|
||||
|
||||
cout << "writing images\n";
|
||||
fs << "images" << "[";
|
||||
|
||||
fs << "image1.jpg" << "myfi.png" << "baboon.jpg";
|
||||
cout << "image1.jpg" << " myfi.png" << " baboon.jpg" << endl;
|
||||
|
||||
fs << "]";
|
||||
|
||||
cout << "writing mats\n";
|
||||
Mat R =Mat_<double>::eye(3, 3),T = Mat_<double>::zeros(3, 1);
|
||||
cout << "R = " << R << "\n";
|
||||
cout << "T = " << T << "\n";
|
||||
fs << "R" << R;
|
||||
fs << "T" << T;
|
||||
|
||||
cout << "writing MyData struct\n";
|
||||
MyData m(1);
|
||||
fs << "mdata" << m;
|
||||
cout << m << endl;
|
||||
}
|
||||
|
||||
//read
|
||||
{
|
||||
FileStorage fs(filename, FileStorage::READ);
|
||||
|
||||
if (!fs.isOpened())
|
||||
{
|
||||
cerr << "failed to open " << filename << endl;
|
||||
help(av);
|
||||
return 1;
|
||||
}
|
||||
|
||||
FileNode n = fs["images"];
|
||||
if (n.type() != FileNode::SEQ)
|
||||
{
|
||||
cerr << "images is not a sequence! FAIL" << endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
cout << "reading images\n";
|
||||
FileNodeIterator it = n.begin(), it_end = n.end();
|
||||
for (; it != it_end; ++it)
|
||||
{
|
||||
cout << (string)*it << "\n";
|
||||
}
|
||||
|
||||
Mat R, T;
|
||||
cout << "reading R and T" << endl;
|
||||
|
||||
fs["R"] >> R;
|
||||
fs["T"] >> T;
|
||||
|
||||
cout << "R = " << R << "\n";
|
||||
cout << "T = " << T << endl;
|
||||
|
||||
MyData m;
|
||||
fs["mdata"] >> m;
|
||||
|
||||
cout << "read mdata\n";
|
||||
cout << m << endl;
|
||||
|
||||
cout << "attempting to read mdata_b\n"; //Show default behavior for empty matrix
|
||||
fs["mdata_b"] >> m;
|
||||
cout << "read mdata_b\n";
|
||||
cout << m << endl;
|
||||
|
||||
}
|
||||
|
||||
cout << "Try opening " << filename << " to see the serialized data." << endl << endl;
|
||||
|
||||
//read from string
|
||||
{
|
||||
cout << "Read data from string\n";
|
||||
string dataString =
|
||||
"%YAML:1.0\n"
|
||||
"mdata:\n"
|
||||
" A: 97\n"
|
||||
" X: 3.1415926535897931e+00\n"
|
||||
" id: mydata1234\n";
|
||||
MyData m;
|
||||
FileStorage fs(dataString, FileStorage::READ | FileStorage::MEMORY);
|
||||
cout << "attempting to read mdata_b from string\n"; //Show default behavior for empty matrix
|
||||
fs["mdata"] >> m;
|
||||
cout << "read mdata\n";
|
||||
cout << m << endl;
|
||||
}
|
||||
|
||||
//write to string
|
||||
{
|
||||
cout << "Write data to string\n";
|
||||
FileStorage fs(filename, FileStorage::WRITE | FileStorage::MEMORY | FileStorage::FORMAT_YAML);
|
||||
|
||||
cout << "writing MyData struct\n";
|
||||
MyData m(1);
|
||||
fs << "mdata" << m;
|
||||
cout << m << endl;
|
||||
string createdString = fs.releaseAndGetString();
|
||||
cout << "Created string:\n" << createdString << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
@ -8,14 +8,14 @@ using namespace std;
|
||||
static void help(char** av)
|
||||
{
|
||||
cout << endl
|
||||
<< av[0] << " shows the usage of the OpenCV serialization functionality." << endl
|
||||
<< av[0] << " shows the usage of the OpenCV serialization functionality." << endl << endl
|
||||
<< "usage: " << endl
|
||||
<< av[0] << " outputfile.yml.gz" << endl
|
||||
<< "The output file may be either XML (xml) or YAML (yml/yaml). You can even compress it by "
|
||||
<< "specifying this in its extension like xml.gz yaml.gz etc... " << endl
|
||||
<< av[0] << " [output file name] (default outputfile.yml.gz)" << endl << endl
|
||||
<< "The output file may be XML (xml), YAML (yml/yaml), or JSON (json)." << endl
|
||||
<< "You can even compress it by specifying this in its extension like xml.gz yaml.gz etc... " << endl
|
||||
<< "With FileStorage you can serialize objects in OpenCV by using the << and >> operators" << endl
|
||||
<< "For example: - create a class and have it serialized" << endl
|
||||
<< " - use it to read and write matrices." << endl;
|
||||
<< " - use it to read and write matrices." << endl << endl;
|
||||
}
|
||||
|
||||
class MyData
|
||||
@ -68,13 +68,16 @@ static ostream& operator<<(ostream& out, const MyData& m)
|
||||
|
||||
int main(int ac, char** av)
|
||||
{
|
||||
string filename;
|
||||
|
||||
if (ac != 2)
|
||||
{
|
||||
help(av);
|
||||
return 1;
|
||||
filename = "outputfile.yml.gz";
|
||||
}
|
||||
else
|
||||
filename = av[1];
|
||||
|
||||
string filename = av[1];
|
||||
{ //write
|
||||
//! [iomati]
|
||||
Mat R = Mat_<uchar>::eye(3, 3),
|
||||
@ -118,7 +121,7 @@ int main(int ac, char** av)
|
||||
//! [close]
|
||||
fs.release(); // explicit close
|
||||
//! [close]
|
||||
cout << "Write Done." << endl;
|
||||
cout << "Write operation to file:" << filename << " completed successfully." << endl;
|
||||
}
|
||||
|
||||
{//read
|
||||
|
@ -9,10 +9,10 @@ def help(filename):
|
||||
'''
|
||||
{0} shows the usage of the OpenCV serialization functionality. \n\n
|
||||
usage:\n
|
||||
python3 {0} outputfile.yml.gz\n\n
|
||||
The output file may be either in XML, YAML or JSON. You can even compress it\n
|
||||
by specifying this in its extension like xml.gz yaml.gz etc... With\n
|
||||
FileStorage you can serialize objects in OpenCV.\n\n
|
||||
python3 {0} [output file name] (default outputfile.yml.gz)\n\n
|
||||
The output file may be XML (xml), YAML (yml/yaml), or JSON (json).\n
|
||||
You can even compress it by specifying this in its extension like xml.gz yaml.gz etc...\n
|
||||
With FileStorage you can serialize objects in OpenCV.\n\n
|
||||
For example: - create a class and have it serialized\n
|
||||
- use it to read and write matrices.\n
|
||||
'''.format(filename)
|
||||
@ -49,7 +49,9 @@ class MyData:
|
||||
def main(argv):
|
||||
if len(argv) != 2:
|
||||
help(argv[0])
|
||||
exit(1)
|
||||
filename = 'outputfile.yml.gz'
|
||||
else :
|
||||
filename = argv[1]
|
||||
|
||||
# write
|
||||
## [iomati]
|
||||
@ -60,8 +62,6 @@ def main(argv):
|
||||
m = MyData()
|
||||
## [customIOi]
|
||||
|
||||
filename = argv[1]
|
||||
|
||||
## [open]
|
||||
s = cv.FileStorage(filename, cv.FileStorage_WRITE)
|
||||
# or:
|
||||
@ -98,7 +98,7 @@ def main(argv):
|
||||
## [close]
|
||||
s.release()
|
||||
## [close]
|
||||
print ('Write Done.')
|
||||
print ('Write operation to file:', filename, 'completed successfully.')
|
||||
|
||||
# read
|
||||
print ('\nReading: ')
|
||||
|
Loading…
Reference in New Issue
Block a user