我正在制作一个使用opencv和zeromq的C ++应用程序。当我尝试通过zmq tcp套接字发送cv :: Mat对象(CV_8UC3)时,我遇到了一些问题。
以下是更新的代码示例:
#include <iostream>
#include <zmq.hpp>
#include <pthread.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace std;
int main()
{
zmq::context_t ctx( 1 );
zmq::socket_t mysocket( ctx, ZMQ_PUSH );
mysocket.bind( "tcp://lo:4050" );
cv::VideoCapture capture( CV_CAP_ANY );
capture.set( CV_CAP_PROP_FRAME_WIDTH, 640 );
capture.set( CV_CAP_PROP_FRAME_HEIGHT, 480 );
cv::Mat3b frame;
capture >> frame; //First one is usually blank
capture >> frame;
capture >> frame;
cv::Mat3b clonedFrame( 480, 640, CV_8UC3 );
frame.copyTo( clonedFrame );
cout << "Original:" << endl
<< "Address of data:\t" << &frame.data << endl
<< "Size:\t\t\t" << frame.total() * frame.channels() << endl << endl;
cout << "Cloned:" << endl
<< "Address of data:\t" << &clonedFrame.data << endl
<< "Size:\t\t\t" << clonedFrame.total() * clonedFrame.channels() << endl << endl;
cout << "Gap between data:\t" << &clonedFrame.data - &frame.data << endl;
unsigned int frameSize = frame.total() * frame.channels();
zmq::message_t frameMsg( frame.data, frameSize, NULL, NULL );
zmq::message_t clonedFrameMsg( clonedFrame.data, frameSize, NULL, NULL );
cv::imshow( "original", frame );
cv::imshow( "cloned", clonedFrame );
cvWaitKey( 0 );
if( frame.isContinuous() )
{
cout << "Sending original frame" << endl;
mysocket.send( frameMsg, 0 ); //This works
cout << "done..." << endl;
}
cvWaitKey( 0 );
if( clonedFrame.isContinuous() )
{
cout << "Sending cloned frame" << endl;
mysocket.send( clonedFrameMsg, 0 ); //This fails
cout << "done..." << endl;
}
return EXIT_SUCCESS;
}
后者send()使zmq失败了一些断言。 输出:
Original:
Address of data: 0xbfdca480
Size: 921600
Cloned:
Address of data: 0xbfdca4b8
Size: 921600
Gap between data: 14
Sending original frame
done...
Sending cloned frame
Bad address
done...
nbytes != -1 (tcp_socket.cpp:203)
为什么clone()弄乱指针,我该如何解决?
感谢任何帮助。
编辑2012-05-25: 更新了代码示例。 我可以通过给出以下指向消息构造函数的指针之一来发送原始帧:frame.ptr(),frame.data,frame.datastart,frame.at()。它们都适用于原始版本,但没有适用于构造函数。 如您所见,两个数据中心之间的地址空间很小。它不应该至少是frameSize?
//约翰
答案 0 :(得分:0)
好的......所以我最终制作了自己的复制功能
看起来像这样:
struct frameData_t
{
unsigned char *data;
size_t size;
};
struct frameData_t *copyMatData( cv::Mat3b &indata )
{
struct frameData_t *ret = new struct frameData_t;
ret->size = indata.total() * indata.channels();
ret->data = new unsigned char[ret->size];
int datapos = 0;
for( int channel = 0; channel < indata.channels(); channel++ )
{
for( int row = 0; row < indata.rows; row++ )
{
const cv::Vec3b *srcrow = indata[row];
for( int col = 0; col < indata.cols; col++, datapos++ )
{
ret->data[datapos] = srcrow[col][channel];
}
}
}
return ret;
}
我这样用它:
struct frameData_t *clonedFrame = copyMatData( frame );
zmq::message_t frameMsg( frame.data, frameSize, NULL, NULL );
mysocket.send( clonedFrameMsg, 0 );
如果有人知道更好的方法,请告诉我。
//约翰