我正在尝试通过TCP连接发送OpenCv Mat。到目前为止,我能够在boost::asio tutorial之后建立一个简单的TCP连接。
我想知道是否可以简单地修改该示例,然后将cv::Mat image_放置在tcp连接对象内字符串message_的位置,或者是否应该使用其他策略为客户端提供图像。
最佳答案
由于您已经使用过Boost,因此不妨查看模块serialization
。以下是将cv::Mat
转换为std::string
的示例:
#include <opencv2/core.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <cassert>
#include <string>
#include <vector>
BOOST_SERIALIZATION_SPLIT_FREE( cv::Mat )
namespace boost {
namespace serialization {
template <class Archive>
void save( Archive & ar, const cv::Mat & m, const unsigned int version )
{
size_t elemSize = m.elemSize();
size_t elemType = m.type();
ar & m.cols;
ar & m.rows;
ar & elemSize;
ar & elemType;
const size_t dataSize = m.cols * m.rows * m.elemSize();
for ( size_t i = 0; i < dataSize; ++i )
ar & m.data[ i ];
}
template <class Archive>
void load( Archive & ar, cv::Mat& m, const unsigned int version )
{
int cols, rows;
size_t elemSize, elemType;
ar & cols;
ar & rows;
ar & elemSize;
ar & elemType;
m.create( rows, cols, static_cast< int >( elemType ) );
const size_t dataSize = m.cols * m.rows * elemSize;
for (size_t i = 0; i < dataSize; ++i)
ar & m.data[ i ];
}
} // namespace serialization
} // namespace boost
std::string save( const cv::Mat & mat )
{
std::ostringstream oss;
boost::archive::text_oarchive toa( oss );
toa << mat;
return oss.str();
}
void load( cv::Mat & mat, const char * data_str )
{
std::stringstream ss;
ss << data_str;
boost::archive::text_iarchive tia( ss );
tia >> mat;
}
int main( int argc, char ** argv )
{
cv::Mat eye = cv::Mat::eye( 3, 3, CV_32FC1 );
std::string serialized = save( eye );
std::cout << "serialized = " << serialized << std::endl;
cv::Mat deserialized;
load( deserialized, serialized.c_str() );
std::cout << "deserialized = \n\n" << deserialized << std::endl;
return 0;
}
关于c++ - 通过C++中的TCP连接发送Opencv Mat,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29347932/