通过ZMQ,跨进程,跨语言传输图片

9 篇文章 0 订阅
5 篇文章 0 订阅

C++客户端:

//============================================================================
// Name        : ZmqClient.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include "zmq.h"
#include <iostream>
#include <codecvt>
#include <string>
#include "base64.h"
#include <opencv2/core.hpp>
#include "opencv2/opencv.hpp"
#include<opencv2/imgcodecs.hpp>
#include<opencv2/highgui.hpp>
using namespace cv;
using namespace std;
//#include "utf8.h"
//imgType 包括png bmp jpg jpeg等opencv能够进行编码解码的文件
//imgType 包括png bmp jpg jpeg等opencv能够进行编码解码的文件
std::string Mat2Base64(const cv::Mat &image, std::string imgType) {
    //Mat转base64
    std::vector<uchar> buf;
    cv::imencode(imgType, image, buf);
    //uchar *enc_msg = reinterpret_cast<unsigned char*>(buf.data());
    std::string img_data = base64_encode(buf.data(), buf.size(), false);
    return img_data;
}

cv::Mat Base2Mat(std::string &base64_data) {
    cv::Mat img;
    std::string s_mat;
    s_mat = base64_decode(base64_data.data(), false);
    std::vector<char> base64_img(s_mat.begin(), s_mat.end());
    img = cv::imdecode(base64_img, cv::IMREAD_COLOR); //CV::IMREAD_UNCHANGED
    return img;
}

bool ReadImageBase64Data(string strImageName,string &strOutBase64) {
	if(strImageName.empty())
	{
		return false;
	}
    FILE *fp = fopen(strImageName.c_str(),"rb");   //二进制模式
    if(NULL == fp )
    {
        return false;
    }
    size_t size = 0;

    fseek(fp,0L,SEEK_END);
    size=ftell(fp);
    fseek(fp,0L,SEEK_SET);

    void *pBuf = (char *)malloc((size + 1) * sizeof(char));
    if(NULL == pBuf)
    {
    	fclose(fp);
    	return false;
    }
    int iReadSize =  fread( pBuf, 1, size, fp);
    strOutBase64 = base64_encode((unsigned char *)pBuf,iReadSize);

    fclose(fp);
    free(pBuf);

	return true;
}
int main() {
    printf ("Connecting to hello world server…\n");

    /*创建一个新的上下文*/
    void *context = zmq_ctx_new ();
    void *requester = zmq_socket (context, ZMQ_REQ);
    /*通过tcp协议,5555端口,连接本机服务端*/
    //zmq_connect (requester, "tcp://192.168.22.150:6666");
    zmq_connect (requester, "tcp://192.30.26.151:7777");
    cout<<"10.30.26.151:7777:"<<endl;
    //zmq_connect (requester, "tcp://*:6666");

    Mat img;
    while(true)
    {

    	char szBuf[200]="";
    	memset(szBuf,0,200);
    	cout<<"请输入文件名:"<<endl;
    	cin>>szBuf;

    	img = imread(szBuf);
    	string strBase64Out;
		//Mat2Base64(img,strBase64Out);
        clock_t start_time1=clock();
    	ReadImageBase64Data(szBuf,strBase64Out);
        clock_t end_time1=clock();
        cout << "Base64 run time is: " <<(double)(end_time1 - start_time1) / CLOCKS_PER_SEC << " s" << endl;
        clock_t start_time=clock();
    	zmq_send (requester, strBase64Out.c_str(), strBase64Out.length(), 0);
      	char buffer [100];
    	zmq_recv (requester, buffer, 10, 0);
        clock_t end_time=clock();
        cout << "The run time is: " <<(double)(end_time - start_time) / CLOCKS_PER_SEC << " s" << endl;

        cout << "All run time is: " <<(double)(end_time - start_time1) / CLOCKS_PER_SEC << " s" << endl;
    	printf ("Receive: %s\n", buffer);
    	sleep(1);
    }


    zmq_close (requester);
    zmq_ctx_destroy (context);

	return 0;
}

python服务端:

import torch

import zmq


# 对图片进行base64编码,解码,解码为numpy,opencv,matplot照片

# USAGE

# python base64_2_jpg.py


import base64

import cv2

import numpy as np

from matplotlib import pyplot as plt


# 将字符串写入文字

#  name 图片名

#  base64_data 图片二进制编码后string流

def write2txt(name, base64_data):

    # 写入_base64.txt

    print(name)

    print(name,len(base64_data))

    basef = open(name + '_base64.txt', 'w')

    data = 'data:image/jpg;base64,%s' % base64_data

    # print(data)

    basef.write(base64_data)

    basef.close()


# 编码图像为base64字符串

def encode_base64(file):

    with open(file, 'rb') as f:

        img_data = f.read()

        base64_data = base64.b64encode(img_data)

        print(type(base64_data))

        # print(base64_data)

        # 如果想要在浏览器上访问base64格式图片,需要在前面加上:data:image/jpeg;base64,

        base64_str = str(base64_data, 'utf-8')

        # print(base64_str)

        print(len(base64_data))

        write2txt(file.replace(".jpg", ""), base64_str)

        return base64_data



# 解码base64字符串为图像,并保存

def decode_base64(base64_data):

    with open('./base64.jpg', 'wb') as file:

        img = base64.b64decode(base64_data)

        file.write(img)



# 解码base64字符串为numpy图像、opencv、matplot图像

# 解码base64字符串为numpy图像

def decode_base64_np_img(base64_data):

    img = base64.b64decode(base64_data)

    img_array = np.fromstring(img, np.uint8)  # 转换np序列

    print('numpy: ', img_array.shape)

    cv2.imshow("img", img_array)

    cv2.waitKey(0)


# 解码base64字符串为opencv图像

def decode_base64_cv_img(base64_data):

    img = base64.b64decode(base64_data)

    img_array = np.fromstring(img, np.uint8)  # 转换np序列

    img_raw = cv2.imdecode(img_array, cv2.IMREAD_COLOR)  # 转换Opencv格式BGR

    img_gray = cv2.imdecode(img_array, cv2.IMREAD_GRAYSCALE)  # 转换灰度图

    print('opencv bgr: ', img_raw.shape)

    print('opencv gray: ', img_gray.shape)

    cv2.imshow("img bgr", img_raw)

    cv2.imshow("img gray", img_gray)

    cv2.waitKey(0)


# 解码base64字符串为matplot图像

def decode_base64_matplot_img(base64_data):

    img = base64.b64decode(base64_data)

    img_array = np.fromstring(img, np.uint8)  # 转换np序列

    img_raw = cv2.imdecode(img_array, cv2.IMREAD_COLOR)  # 转换Opencv格式BGR

    img_matplot = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)  # BGR转RGB



    img_gray = cv2.imdecode(img_array, cv2.IMREAD_GRAYSCALE)  # 转换灰度图

    imggray_matplot = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)  # 灰度图转RGB

    plt.figure()

    plt.title("Matplot RGB Origin Image")

    plt.axis("off")

    plt.imshow(img_matplot)

    plt.figure()

    plt.title("Matplot Gray Origin Image")

    plt.axis("off")

    plt.imshow(imggray_matplot)

    plt.show()



#if __name__ == '__main__':

#    img_path = './images/1622175322109_0.025711.jpg'

#    base64_data = encode_base64(img_path)

#    decode_base64(base64_data)



#    decode_base64_np_img(base64_data)

#    decode_base64_cv_img(base64_data)

#    decode_base64_matplot_img(base64_data)


context = zmq.Context()

socket = context.socket(zmq.REP)

socket.bind("tcp://*:6666")


def detect(save_img=False):

    while True:
        try:
            print("wait for client ...")
            message = socket.recv()
            #message = message.decode().strip(b'\x00'.decode())

            #print("message from client:", message)

            decode_base64(message) 
            socket.send_string("Ok")

        except Exception as e:

            print('异常:',e)

            socket.send_string("0.01"+"&"+"0.01")

if __name__ == '__main__':

    detect()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

设备系统软件集成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值