http发送和接收图片json文件

 一、http数据发送

1、先将图片转换为base64格式

std::string detectNet::Mat2Base64(const cv::Mat &image, std::string imgType){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;
}

2、将数据以json格式进行发送

void detectNet::send_json_people(cv::Mat img, std::string label, std::string level, std::string rtsp){std::string out = Mat2Base64(img,".jpg");//std::cout << out << std::endl;ImgInfo imgInfo(out, label, level, rtsp);static auto client = httplib::Client("127.0.0.1", 18080);auto result = client.Post("/uploadAlgorithmResult", imgInfo.to_json_people(), "application/json");if (result != nullptr && result->status == 200) {std::cout << result->body << std::endl;}
}

其中 ImgInfo 类为:

#ifndef HTTP_DEMO_IMGINFO_H
#define HTTP_DEMO_IMGINFO_H#include <utility>#include "cJSON.h"
#include "base64.h"#define RTSP_URL "rtsp://admin:a123456789@192.168.8.31:554/h264/ch1/main/av_stream/1"
#define AlgorithmType "hook_detection"
#define AlgorithmType_people "danger_zone"
#define AlgorithmType_crooked "crooked"class ImgInfo {
private:std::string img;std::string label;std::string rtsp;std::string level;
public:ImgInfo(std::string img, std::string label, std::string level, std::string rtsp) : img(std::move(img)), label(std::move(label)),level(std::move(level)), rtsp(std::move(rtsp)) {}std::string to_json_people() {auto *root = cJSON_CreateObject();cJSON_AddStringToObject(root, "image", img.c_str());cJSON_AddStringToObject(root, "level", level.c_str());cJSON_AddStringToObject(root, "rtsp", rtsp.c_str());cJSON_AddStringToObject(root, "type", AlgorithmType_people);cJSON_AddStringToObject(root, "label", label.c_str());/*cJSON *label_array = cJSON_CreateArray();for (auto &i: label) {cJSON_AddItemToArray(label_array, cJSON_CreateString(i.c_str()));}cJSON_AddItemToObject(root, "label", label_array);*/char *out = cJSON_Print(root);std::string res = out;free(out);cJSON_Delete(root);return res;}
};#endif //HTTP_DEMO_IMGINFO_H

上述代码中json数据有五个部分:image为图片数据,level是告警等级,rtsp为数据流地址,type是算法类型,label是算法标签等,所以数据发送为这五个内容。

二、http数据接收

HttpServer.cpp如下: 

//#include <QFile>
//#include <FileUtils.hpp>
#include "HttpServer.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//#include "QString"
//#include "TimeUtils.hpp"
//#include "AlgorithmCommon.h"
//#include "QJsonObject"
//#include "QJsonDocument"
//#include "QJsonArray"
//#include "httplib.h"//#include "log.h"
//#include "cJSON.h"HttpServer::HttpServer(std::string ip, int port) : server_ip(ip), server_port(port) {//event_handler = new AlgorithmAlarmHandler();}HttpServer::~HttpServer() {stopListen();if (read_thd.joinable()) {read_thd.join();}
}void HttpServer::startListen() {read_thd = std::thread([=]() {serverListen();});//event_handler->startHandlerThread();
}void HttpServer::stopListen() {if (server.is_running()) {server.stop();}
}void HttpServer::serverListen() {if (!server.is_valid()) {std::cout << "http server invalid" << std::endl;return;}// 服务器状态server.Get("/server/status", [&](const Request &req, Response &res) {onServerStatus(req, res);});// 上传算法结果server.Post("/uploadAlgorithmResult", [&](const Request &req, Response &res) {onUploadAlgorithmResult(req, res);});// 错误处理server.set_error_handler([&](const Request &req, Response &res) {onErrorHandle(req, res);});//qDebug() << "server start listen";server.listen(server_ip.c_str(), server_port);
}void HttpServer::onServerStatus(const httplib::Request &req, httplib::Response &res) {res.body = R"({"code": 200,"msg": "Server is already Running"})";
}void HttpServer::onUploadAlgorithmResult(const httplib::Request &req, httplib::Response &res) {std::string content_type = httputillib::GetContentType(req.headers);//if (content_type != "application/json") {//     qDebug() << "contentType 异常, content_type:" << QString::fromStdString(content_type);//}bool parseRet = parseAlgorithmResult(req.body);//bool parseRet = true;std::string rspMsg;if (parseRet) {rspMsg = std::string(R"({"msg":"Recv Success, Parse Success."})");} else {rspMsg = std::string(R"({"msg":"Recv Success, Parse Failed."})");}res.body = std::move(rspMsg);
}// 错误请求处理
void HttpServer::onErrorHandle(const httplib::Request &req, httplib::Response &res) {const char *fmt = {"\"error\": \"服务器不支持该方法\""};char buf[BUFSIZ] = {0};snprintf(buf, sizeof(buf), fmt, res.status);res.set_content(buf, "application/json");
}bool HttpServer::parseAlgorithmResult(const std::string &body) {//std::cout << "body:" << body << std::endl;Json::Reader reader;Json::Value root;//std::ifstream in(body, std::ios::binary);//if (!in.is_open()) {//    std::cout << "open file failed" << std::endl;//    return false;//}if (!reader.parse(body, root)) {std::cout << "parse failed" << std::endl;return false;}std::string rtsp = root["rtsp"].asString();std::cout << "rtsp:" << rtsp << std::endl;std::string level = root["level"].asString();std::cout << "level:" << level << std::endl;std::string type = root["type"].asString();std::cout << "type:" << type << std::endl;std::string image = root["image"].asString();//std::cout << "image:" << image << std::endl;std::string out = base64_decode(image);std::string decoded_jpeg = std::move(out);//std::cout << "decoded_jpeg: " << decoded_jpeg << std::endl;cv::Mat mat2(1, decoded_jpeg.size(), CV_8U, (char*)decoded_jpeg.data());cv::Mat dst = cv::imdecode(mat2, CV_LOAD_IMAGE_COLOR);cv::imwrite(rtsp.substr(1) + ".jpg", dst);  return true;
}

 HttpServer.h如下:

//#ifndef CPPHTTPSERVER_HTTPSERVER_H
//#define CPPHTTPSERVER_HTTPSERVER_H#include "httputillib.h"
#include "httplib.h"
#include "base64.h"
//#include "thread"
#include <thread>
#include <time.h>#include <json.h>class HttpServer{
public:HttpServer(std::string ip, int port);~HttpServer();void startListen();void stopListen();private:void serverListen();// 回调函数: 错误请求处理void onErrorHandle(const httplib::Request &req, httplib::Response &res);// 回调函数: 获取服务器状态void onServerStatus(const httplib::Request &req, httplib::Response &res);// 回调函数: 上传算法结果void onUploadAlgorithmResult(const httplib::Request &req, httplib::Response &res);// 回调函数:处理算法数据bool parseAlgorithmResult(const std::string &body);std::string server_ip;int server_port;Server server;std::thread read_thd;};//#endif //CPPHTTPLIB_HTTPLIB_H

httputillib.h如下:

#include <httplib.h>using namespace httplib;namespace httputillib {
// 打印请求头
static std::string DumpHeaders(const Headers &headers) {std::string s;char buf[BUFSIZ] = {0};for (auto it = headers.begin(); it != headers.end(); ++it) {const auto &x = *it;snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());s += buf;}return s;
}// 从请求同获取content type
static std::string GetContentType(const httplib::Headers &headers) {auto iter = headers.find("Content-Type");if (iter == headers.end()) {return std::string();}return iter->second;
}};

上述完整代码可详见github或者百度网盘

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/100541.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【每日一题】AcWing 5271. 易变数 | 思维 | 中等

题目内容 原题链接 给定一个二进制表示的数 s s s 。 定义函数 f ( x ) f(x) f(x) 为 x x x 的二进制位中为 1 1 1 的数量。每次操作可以使得 x → f ( x ) x\rightarrow f(x) x→f(x) &#xff0c;问在最少操作次数下&#xff0c;恰好 k k k 次操作后为 1 1 1 的数有多…

Spring Security 6.1.x 系列 (1)—— 初识Spring Security

一、 Spring Security 概述 Spring Security是Spring组织提供的一个开源安全框架&#xff0c;基于Spring开发&#xff0c;所以非常适合在Spring Boot中使用。 官方文档地址&#xff1a;https://docs.spring.io/spring-security/reference/index.html GitHub地址&#xff1a;…

智能视频监控,究竟“智”在哪里?

当人们一提到智能视频监控时&#xff0c;就会想起高清摄像头、人脸识别等技术。其实不然&#xff0c;真正智能视频监控不仅仅是这些技术算法&#xff0c;更重要的是如何将这些算法融入到应用场景中&#xff0c;更好地去服务大众、起到降本增效的作用。 首先&#xff0c;智能视…

数据结构和算法(10):B-树

B-树&#xff1a;大数据 现代电子计算机发展速度空前&#xff0c;就存储能力而言&#xff0c;情况似乎也是如此&#xff1a;如今容量以TB计的硬盘也不过数百元&#xff0c;内存的常规容量也已达到GB量级。 然而从实际应用的需求来看&#xff0c;问题规模的膨胀却远远快于存储能…

Transformer为什么如此有效 | 通用建模能力,并行

目录 1 更强更通用的建模能力 2 并行计算 3 大规模训练数据 4 多训练技巧的集成 Transformer是一种基于自注意力机制的网络&#xff0c;在最近一两年年可谓是大放异彩&#xff0c;我23年入坑CV的时候&#xff0c;我看到的CV工作似乎还没有一个不用到Transformer里的一些组…

解决 Git:This is not a valid source path/URL

由于sourcetree 可以获取不同仓库的代码&#xff0c;而我的用户名密码比较杂乱&#xff0c;导致经常会修改密码&#xff0c;在新建拉去仓库代码的时候sourcetree 不会提示你密码错误&#xff0c;直接提示 This is not a valid source path/URL。 在已存在的代码仓库&#xff0…

TDengine+OpenVINO+AIxBoard,助力时序数据分类

时间序列数据分析在工业&#xff0c;能源&#xff0c;医疗&#xff0c;交通&#xff0c;金融&#xff0c;零售等多个领域都有广泛应用。其中时间序列数据分类是分析时序数据的常见任务之一。本文将通过一个具体的案例&#xff0c;介绍 Intel 团队如何使用 TDengine 作为基础软件…

rocketmq消息发送源码学习

消息发送基本流程 消息发送流程主要的步骤&#xff1a;验证消息、查找路由、消息发送&#xff08;包含异常处理机制&#xff09;。 代码&#xff1a;同步消息发送入口 DefaultMQProducer#send public SendResult send(Message msg) throws MQClientException, RemotingExcep…

golang singleflight资料整理

https://www.cyningsun.com/01-11-2021/golang-concurrency-singleflight.html https://juejin.cn/post/7261897250648817701 https://segmentfault.com/q/1010000022916754 https://juejin.cn/post/6916785233509482509 https://segmentfault.com/a/1190000018464029

备忘录模式 行为型模式之八

1.定义 备忘录模式是一种行为型的软件设计模式&#xff0c;在不破坏封装的前提下&#xff0c;获取一个对象的内部状态&#xff0c;并在对象外保存该状态&#xff0c;当对象需要恢复到该状态时&#xff0c;对其进行恢复。 2.组成结构 原发器 &#xff08;Originator&#xff0…

超详细!主流大语言模型的技术原理细节汇总!

1.比较 LLaMA、ChatGLM、Falcon 等大语言模型的细节&#xff1a;tokenizer、位置编码、Layer Normalization、激活函数等。 2. 大语言模型的分布式训练技术&#xff1a;数据并行、张量模型并行、流水线并行、3D 并行、零冗余优化器 ZeRO、CPU 卸载技术 ZeRo-offload、混合精度训…

pip安装或更新

在终端用pip安装时老是报错&#xff0c;把pip升级到最高版本还是不行 ERROR: Exception: Traceback (most recent call last): File "F:\software\anaconda\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 438, in _error_catcher yiel…

gcc和g++区别

一、什么是GNU编译器? GNU编译器&#xff08;GNU Compiler Collection&#xff0c;简称GCC&#xff09;&#xff0c;是一套由自由软件基金会所发展的编程器。GCC支持多种编程语言&#xff0c;包括C、C、Objective-C、Fortran、Ada、以及其它一些语言。它是Linux系统和很多类U…

Zabbix监控硬盘S.M.A.R.T.信息教程

S.M.A.R.T.是"Self-Monitoring, Analysis, and Reporting Technology"的缩写&#xff0c;它是一种硬盘自我监测、分析和报告技术。硬盘S.M.A.R.T.信息的主要用途是帮助用户和系统管理员监测硬盘的健康状态和性能&#xff0c;例如温度、振动、读写错误率、坏道数量等&…

Linux 部署 MinIO 分布式对象存储 配置为 typora 图床

前言 MinIO 是一款高性能的对象存储系统&#xff0c;它可以用于大规模的 AI/ML、数据湖和数据库工作负载。它的 API 与Amazon S3 云存储服务完全兼容&#xff0c;可以在任何云或本地基础设施上运行。MinIO 是开源软件&#xff0c;也提供商业许可和支持 MinIO 的特点有&#x…

用Jmeter进行接口自动化测试的工作流程你知道吗?

在测试负责人接受到测试任务后&#xff0c;应该按照以下流程规范完成测试工作。 2.1 测试需求分析 产品开发负责人在完成某产品功能的接口文档编写后&#xff0c;在核对无误后下发给对应的接口测试负责人。测试负责人拿到接口文档需要首先做以下两方面的工作。一方面&#…

点云采样方法

随机采样&#xff0c;网格采样&#xff0c;均匀采样&#xff0c;集合采样。 网格采样&#xff1a;用规则的网格对点进行采样&#xff0c;不能精确的控制采样点的数量 均匀采样&#xff1a;均匀的采样点云中的点&#xff0c;由于其鲁棒性(系统的健壮性)而更受欢迎 点云降采样…

Windows11更新后Chrome无法打开解决方案

引言 最近更新了win11后&#xff0c;chrome突然抽风无法打开了&#xff0c;不知道是不是微软的锅&#xff0c;上网查询发现似乎有很多人最近碰到了相同的问题&#xff0c;试了试最为广泛传播的方案–更改manifest文件。然而在我这无效&#xff0c;索性直接重装&#xff0c;发现…

vscode搭建c/c++环境

1. 安装mingw64 2.vscode安装c/c插件&#xff0c;run插件 3.在workspace/.vscode文件夹下新建三个文件&#xff1a; 1&#xff09;c_cpp_properties.json { "configurations": [ { "name": "Win32", "includePath": [ "${wor…

CentOS8的nmcli常用命令总结

nmcli常用命令 # 查看ip&#xff08;类似于ifconfig、ip addr&#xff09; nmcli# 创建connection&#xff0c;配置静态ip&#xff08;等同于配置ifcfg&#xff0c;其中BOOTPROTOnone&#xff0c;并ifup启动&#xff09; nmcli c add type ethernet con-name ethX ifname ethX…