将 OpenCV-Matrix 转换为矢量

Cast OpenCV-Matrix to vector

本文关键字:转换 OpenCV-Matrix      更新时间:2023-10-16

如何将OpenCV矩阵转换为尽可能多的OpenCV类型的std::vector(例如cv::Mat_<T>cv::Matx<T,M,N>(?以下内容似乎不起作用,因为cv::Matx没有begin方法:

template <class T>
inline void foo(const T& data)
{
using value_type = typename T::value_type;
std::vector<value_type> v(data.begin(), data.end());
}

在@rafix07的建议下,我找到了解决方案:

#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>
template <class... T>
struct make_void
{
using type = void;
};
template <class... T>
using void_t = typename make_void<T...>::type;
template <class E, class = void>
struct has_iterator_interface : std::false_type
{
};
template <class E>
struct has_iterator_interface<E, void_t<decltype(std::declval<E>().begin())>>
: std::true_type
{
};
template <class T, typename = void>
struct as_vector
{
inline static auto get(const T& t)
{
using value_type = typename T::value_type;
cv::Mat_<value_type> s(t, false);
return std::vector<value_type>(s.begin(), s.end());
}
};
template <class T>
struct as_vector<T, typename std::enable_if_t<has_iterator_interface<T>::value>>
{
inline static auto get(const T& t)
{
using value_type = typename T::value_type;
return std::vector<value_type>(t.begin(), t.end());
}
};
int main()
{
cv::Mat_<double> A(2, 3, 0.0);
A(0, 0) = 0.0;
A(0, 1) = 1.0;
A(0, 2) = 2.0;
A(1, 0) = 3.0;
A(1, 1) = 4.0;
A(1, 2) = 5.0;
cv::Matx<double, 3, 4> B;
B(0, 0) = 0.0;
B(0, 1) = 1.0;
B(0, 2) = 2.0;
B(1, 0) = 3.0;
B(1, 1) = 4.0;
B(1, 2) = 5.0;
std::vector<double> a = as_vector<decltype(A)>::get(A);
std::vector<double> b = as_vector<decltype(B)>::get(B);
}

但是,我希望有更简单的东西。