ZeroMQ+OpenCV实现视频网络传输

目录

  • 服务器端
  • 客户端

服务器端

从摄像头捕获图像,并发送数据

#include 
#include 
#include 
#include 

int main()
{
	zmq::context_t context(1);
	zmq::socket_t socket(context, zmq::socket_type::pub);
	socket.bind("tcp://*:5555");


	cv::VideoCapture cap(0);
	if (cap.isOpened())
	{
		std::cout << "摄像头已打开" << std::endl;
		std::cout << "图像宽度" << cap.get(cv::CAP_PROP_FRAME_WIDTH) << std::endl;
		std::cout << "图像高度" << cap.get(cv::CAP_PROP_FRAME_HEIGHT) << std::endl;
	}
	else
		return -1;

	cv::Mat frame;

	while (cap.read(frame))
	{
		cv::Size dstSize = cv::Size(1280,960);
		cv::Mat dstFrame;
		cv::resize(frame, dstFrame, dstSize);

		std::vector<uint8_t> imageBuffer;
		std::vector<int> compress_params;
		compress_params.push_back(cv::IMWRITE_JPEG_QUALITY);
		compress_params.push_back(40);//压缩为原图像的x%,x in [0,100]
		cv::imencode(".jpg", dstFrame, imageBuffer, compress_params);
		
		//send img
		zmq::message_t msg(imageBuffer.size());
		memcpy(msg.data(), imageBuffer.data(), imageBuffer.size());
		socket.send(msg, zmq::send_flags::dontwait);

		std::cout<<"send image, len:"<<imageBuffer.size() << std::endl;
		cv::imshow("pub", dstFrame);
		cv::waitKey(1000 / cap.get(cv::CAP_PROP_FPS));
	}
	return 0;
}

客户端

接受数据并显示

#include 
#include 
#include 


int main(int argc, char* argv[])
{
    zmq::context_t context(1);
    zmq::socket_t socket(context, zmq::socket_type::sub);
    socket.connect("tcp://localhost:5555");
    socket.set(zmq::sockopt::subscribe, "");//设置过滤条件,这里为空,表示接收所有信息

    cv::Mat frame;
    while (true) 
    {
        zmq::message_t msg;
        auto ok = socket.recv(msg, zmq::recv_flags::dontwait);
        if (ok) 
        {
            std::vector<uint8_t> buffer;
            buffer.resize(msg.size());
            memcpy(buffer.data(), msg.data(), msg.size());

            std::cout<<"receive image, len:"<<msg.size() << std::endl;
            //decode
            frame = cv::imdecode(buffer, cv::IMREAD_COLOR);
            
            cv::imshow("sub", frame);
            //cv::imwrite("receive.jpg", frame);
            cv::waitKey(1);
        }
    }
    return 0;
}

你可能感兴趣的:(计算机网络,opencv,网络)