c#和python的flask接口的交互
一、灰度图像的传输
c#端的传输
//读入文件夹中的图像
Mat img2 = new Mat(file, ImreadModes.AnyColor);
//将图像的数据转换成和相机相同的buffer数据
byte[] image_buffer = new byte[img2.Width * img2.Height];
int cn = img2.Channels(); //通道数
if (cn == 1){//将图像的数据转换成和相机相同的buffer数据Marshal.Copy(img2.Data, image_buffer, 0, img2.Width * img2.Height);}#传输
string result = RequestsPostbuffer(Url, image_buffer);
python 端的解析
receiveData = request.get_data() #相机的buffer转换使用img_cv=np.frombuffer(receiveData,dtype=np.uint8).reshape(1024,1224) #opencv格式
二、彩色图像的传送
c#端的传输
//打开图像,将图像转换成buffer用下面这段代码if (OpenFileDialog1.ShowDialog() == DialogResult.OK){//读入文件夹中的图像Mat img2 = new Mat(OpenFileDialog1.FileName, ImreadModes.AnyColor);byte[] image_buffer = new byte[img2.Width * img2.Height*3];int cn = img2.Channels(); //通道数if (cn == 3){string show_mssage = "测试图像的通道数是:" + Convert.ToString(cn);//将图像的数据转换成和相机相同的buffer数据listBox1.Items.Add(show_mssage);Marshal.Copy(img2.Data, image_buffer, 0, img2.Width * img2.Height);}else{string show_mssage = "错误!!!!!!!!!!!!测试图像需要单通道的灰度图";listBox1.Items.Add(show_mssage);}
python 端的解析
#相机的buffer转换使用img_cv=np.frombuffer(receiveData,dtype=np.uint8).reshape(4096,3500,3) #opencv格式
三、整个工程的实现
python 端的实现
# !/usr/bin/python
# -*- coding: UTF-8 -*-
# python服务器如果需要访问静态的文件,都需要放到static这个指定的文件夹。from flask import Flask, jsonify, request
from flask import render_template
from wtforms import StringField, Form
from wtforms.validators import DataRequiredimport jsonimport cv2
import numpy as npfrom comparison_boxandpdf import Comparison_boxandpdf
from skimage.segmentation import mark_boundariesfrom PIL import Imageimport timeimport base64
import io
from io import BytesIO import easyocrimport halcon as ha
from halcon.numpy_interop import himage_from_numpy_array
from halcon.numpy_interop import himage_as_numpy_arrayfrom gevent import pywsgiimport requestsfrom algorithm_configuration import Read_iniconfig#异常码定义
miss_model = 0 try:#*********************************初始化******************************Comparison_tools=Comparison_boxandpdf()#配置文件解析,主要是根据配置文件中pdf的路径解析出pdf的图像config_Path = 'C:/code/box_ocr/cinfig_ini/algorithm_configuration.ini'read_ini=Read_iniconfig(config_Path)read_bool,dict=read_ini.read_pdfbox_detection_cfg()#模型及图像检测加速初始化pdfbox_model_path=dict.get('pdfbox_model_path')pdfbox_ini_image_path=dict.get('pdfbox_ini_image_path')pdfbox_pdf_path=dict.get('pdfbox_pdf_path')pdfbox_easyocr_thresh=float(dict.get('pdfbox_easyocr_thresh'))print("模型路径",pdfbox_model_path)print("模型初始化加速测试图像的路径为:",pdfbox_ini_image_path)print("阈值",pdfbox_easyocr_thresh)print("PDF的路径为",pdfbox_pdf_path)# #先加载字符识别模型# img_init = cv2.imread(pdfbox_ini_image_path)# reader = easyocr.Reader(['ch_sim', 'en'], gpu=True) # 使用GPU加速# results_init = reader.readtext(img_init)halcon_find_txt_model_path='C:/code/box_ocr/model/Document_Rej.omc'except Exception as e:print("模型路径或者测试图像的路径不正确 ", e)
finally:print("***********************************************算法初始化完成。可以进行通信进行检测********************************")app = Flask(__name__)
app.logger.info('Finished Start Flask!')# 开始数据转移
@app.route('/BOX_OCR/', methods=['POST'])
def startTransfer(name=None):if request.method == 'POST':receiveData = request.get_data() # 接收图像的buffer数据 时间1ms#相机的buffer转换使用img_cv=np.frombuffer(receiveData,dtype=np.uint8).reshape(4096,3500,3) #opencv格式save_image_path_pdf='C:/code/box_ocr/debug_image_show/warpPerspective_result/empty_image_rectification.bmp'cv2.imwrite(save_image_path_pdf,img_cv)error_code=1if(error_code==1):data = {'pdf_pdf': 1,'image_path':1,'number_diff_result':1,'image_result':encoded_image,'image_result_pdf':encoded_image_pdf}else:encoded_image="no"encoded_image_pdf="no"data = {'pdf_pdf': 1,'image_path': 1,'number_diff_result':1,'image_result':encoded_image,'image_result_pdf':encoded_image_pdf}json_data = json.dumps(data)return json_dataif __name__ == '__main__':# app.run(host='127.2.2.0', port=8001, debug=True, threaded=True)# debug=True 时设置的多线程无效# 多线程和多进程功能只能开一个 1.processes=True 2.threaded=Trueserver = pywsgi.WSGIServer(('127.2.2.0', 8001), app)server.serve_forever()
c#端的实现
//选择待检测的PDF的文件private void Button_读取图片2_Click(object sender, EventArgs e){OpenFileDialog1.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF";OpenFileDialog1.Title = "选择图像文件";int hv_Height, hv_Width;string log = "";//错误信息if (OpenFileDialog1.ShowDialog() == DialogResult.OK){// 获取选中的文件路径image_path= OpenFileDialog1.FileName;//string show_mssage = OpenFileDialog1.FileName;//listBox1.Items.Add(image_path);string show_mssage = "待检测的PDF文件的位置为:" + pdf_path;string show_mssage2 = "待检测的图像文件的位置为:" + image_path;listBox1.Items.Add(show_mssage);listBox1.Items.Add(show_mssage2);string path_totall = pdf_path + image_path;List<string> stringsList = new List<string>();stringsList.Add(pdf_path);stringsList.Add(image_path);string jsonParams = pdf_path + "#" + image_path;string paraUrlCoded = jsonParams;//System.Web.HttpUtility.UrlEncode(jsonParas); byte[] payload;//将Json字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(jsonParams);string Url = "http://127.2.2.0:8001//BOX_OCR/";//功能网址string result = RequestsPostbuffer(Url, payload);if (result == null){MessageBox.Show("结果传回出错!", "提示:");}else{if (result.Contains("default")){log = "There is an error running the algorithm." + "\r\n" + result;}else{//对传送回来的结果进行解析//解析对象JObject JObject jo = (JObject)JsonConvert.DeserializeObject(result);string pdf_pdf = jo["pdf_pdf"].ToString();string image_path = jo["image_path"].ToString();string number_diff_result = jo["number_diff_result"].ToString();string image_result = jo["image_result"].ToString();string image_result_pdf = jo["image_result_pdf"].ToString();Console.WriteLine("pdf的路径为:" + pdf_pdf);Console.WriteLine("图像的路径为:" + image_path);Console.WriteLine("检测到的不同之处的个数为:" + number_diff_result);//解析算法处理后绘制处理后的图像-----------通过测试,回传结果图像的用时10ms不到image_result = image_result.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换byte[] result_image_buffer = Convert.FromBase64String(image_result);image_result_pdf = image_result_pdf.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换byte[] result_image_buffer_pdf = Convert.FromBase64String(image_result_pdf);//显示图像MemoryStream memStream = new MemoryStream(result_image_buffer);Image mImage = Image.FromStream(memStream);hv_Width = mImage.Width;hv_Height = mImage.Height;MemoryStream memStrea_pdf = new MemoryStream(result_image_buffer_pdf);Image mImage_pdf = Image.FromStream(memStrea_pdf);if (PictureBox1.Image != null) PictureBox1.Image.Dispose();if (PictureBox2.Image != null) PictureBox2.Image.Dispose();//PictureBox1.Image = mImage.Clone(new Rectangle(0, 0, mImage.Width, mImage.Height), mImage.PixelFormat);PictureBox1.Image = mImage_pdf;PictureBox2.Image = mImage;log = "单张图像测试成功。可以继续测试!!!!";listBox1.Items.Add(log);}}}else{MessageBox.Show("选择有误!", "提示:");}}/// <summary>/// 通过网络地址和端口访问数据/// </summary>/// <param name="Url">网络地址</param>/// <param name="payload">图像的buffer数据</param>/// <returns></returns>/// 客户端创建一个HTTPRequsetpublic string RequestsPostbuffer(string Url, byte[] payload){//*****************************************将客户端这边要传入的数据,进行数据 格式的转换,发送到服务端*******************************************string postContent = ""; // 接收服务端结果的字符串string strURL = Url;//创建一个HTTP请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);//Post请求方式 request.Method = "POST";//内容类型 表示具体请求中的媒体类型信息,application/json表示 JSON数据格式,可以传图像格式。二进制流等,参考链接:https://www.cnblogs.com/doit8791/p/7609413.htmlrequest.ContentType = "application/octet-stream";//设置请求的ContentLength 设置要发布的字符串的内容长度。request.ContentLength = payload.Length;//发送请求,获得请求流 Stream writer;try{writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象}catch (Exception){writer = null;MessageBox.Show("连接服务器失败!");return null;}//将请求参数写入流writer.Write(payload, 0, payload.Length);writer.Close();//关闭请求流//****************************************解析服务端处理的结果并返回处理结果给主程序********************************HttpWebResponse response;//检查是否收到服务端的回应,如果没有回应则错误提示try{//获得响应流response = (HttpWebResponse)request.GetResponse();}catch (WebException ex){response = ex.Response as HttpWebResponse;postContent = "default: The response is null." + "\r\n" + "Exception: " + ex.Message;}//对服务端接收到的数据进行解析if (response != null){try{//收到服务端给的回复流Stream s = response.GetResponseStream();//=创建一个读流的工具StreamReader sRead = new StreamReader(s);//将读取的结果的传送给字符串postContent = sRead.ReadToEnd();//关闭读取流工具sRead.Close();}catch (Exception e){postContent = "default: The data stream is not readable." + "\r\n" + e.Message;}}//将在服务端收到的解析数据回传,回传回去的是一个字符串的类型return postContent;//返回Json数据}
相关文章:
c#和python的flask接口的交互
一、灰度图像的传输 c#端的传输 //读入文件夹中的图像 Mat img2 new Mat(file, ImreadModes.AnyColor); //将图像的数据转换成和相机相同的buffer数据 byte[] image_buffer new byte[img2.Width * img2.Height]; int cn img2.Channels(); //通道数 if (cn 1){//将图像的数…...

Python测试框架Pytest的参数化详解
上篇博文介绍过,Pytest是目前比较成熟功能齐全的测试框架,使用率肯定也不断攀升。 在实际工作中,许多测试用例都是类似的重复,一个个写最后代码会显得很冗余。这里,我们来了解一下pytest.mark.parametrize装饰器&…...

KernelSU 如何不通过模块,直接修改系统分区
刚刚看了术哥发的视频,发现kernelSU通过挂载OverlayFS实现无需模块,即可直接修改系统分区,很是方便,并且安全性也很高,于是便有了这篇文章。 下面的教程与原视频存在差异,建议观看原视频后再结合本文章进行操作。 在未进行修改前,我们打开/system/文件夹,并在里面创建…...

红日靶场ATTCK 1通关攻略
环境 拓扑图 VM1 web服务器 win7(192.168.22.129,10.10.10.140) VM2 win2003(10.10.10.135) VM3 DC win2008(10.10.10.138) 环境搭建 win7: 设置内网两张网卡,开启…...

CellMarker | 人骨骼肌组织细胞Marker大全!~(强烈建议火速收藏!)
1写在前面 分享一下最近看到的2篇paper关于骨骼肌组织的细胞Marker,绝对的Atlas级好东西。👍 希望做单细胞的小伙伴觉得有用哦。😏 2常用marker(一) general_mrkrs <- c( MYH7, TNNT1, TNNT3, MYH1, MYH2, "C…...
游戏名台词大赏
文章目录 原神(圈内) 崩坏:星穹铁道(圈内) 崩坏3(圈内) 原神 只要不失去你的崇高,整个世界都会为你敞开。 总会有地上的生灵,敢于直面雷霆的威光。 谁也没有见过风&…...

OpenCV如何在图像中寻找轮廓(60)
返回:OpenCV系列文章目录(持续更新中......) 上一篇:OpenCV如何模板匹配(59) 下一篇 :OpenCV检测凸包(61) 目标 在本教程中,您将学习如何: 使用 OpenCV 函数 cv::findContours使用 OpenCV 函数 cv::d rawContours …...

java 泛型题目讲解
泛型的知识点 泛型仅存在于编译时期,编译期间JAVA将会使用Object类型代替泛型类型,在运行时期不存在泛型;且所有泛型实例共享一个泛型类 public class Main{public static void main(String[] args){ArrayList<String> list1new Arra…...
pptx 文件版面分析-- python-pptx(python 文档解析提取)
安装 pip install python-pptx -i https://pypi.tuna.tsinghua.edu.cn/simple --ignore-installedpptx 解析代码实现 from pptx import Presentation file_name "rag_pptx/test1.pptx" # 打开.pptx文件 ppt Presentation(file_name) for slide in ppt.slides:#pr…...

http的basic 认证方式
写在前面 本文看下http的basic auth认证方式。 1:什么是basic auth认证 basic auth是一种http协议规范中的一种认证方式,即一种证明你就是你的方式。更进一步的它是一种规范,这种规范是这样子,如果是服务端使用了basic auth认证…...
【信息系统项目管理师练习题】信息系统治理
IT治理的核心是关注以下哪项内容? a) 人员培训和发展计划 b) IT定位和信息化建设与数字化转型的责权利划分 c) 业务流程的绩效管理 d) IT基础设施的优化利用 答案: b) IT定位和信息化建设与数字化转型的责权利划分 IT治理体系框架的组成部分包括以下哪些? a) IT战略目标、IT治…...

RabbitMQ之顺序消费
什么是顺序消费 例如:业务上产生者发送三条消息, 分别是对同一条数据的增加、修改、删除操作, 如果没有保证顺序消费,执行顺序可能变成删除、修改、增加,这就乱了。 如何保证顺序性 一般我们讨论如何保证消息的顺序性&…...

轻松上手的LangChain学习说明书
一、Langchain是什么? 如今各类AI模型层出不穷,百花齐放,大佬们开发的速度永远遥遥领先于学习者的学习速度。。为了解放生产力,不让应用层开发人员受限于各语言模型的生产部署中…LangChain横空出世界。 Langchain可以说是现阶段…...

【论文笔记】Training language models to follow instructions with human feedback A部分
Training language models to follow instructions with human feedback A 部分 回顾一下第一代 GPT-1 : 设计思路是 “海量无标记文本进行无监督预训练少量有标签文本有监督微调” 范式;模型架构是基于 Transformer 的叠加解码器(掩码自注意…...
嵌入式交叉编译:x265
下载 multicoreware / x265_git / Downloads — Bitbucket 解压编译 BUILD_DIR${HOME}/build_libs CROSS_NAMEaarch64-mix210-linuxcd build/aarch64-linuxmake cleancmake \-G "Unix Makefiles" \-DCMAKE_C_COMPILER${CROSS_NAME}-gcc \-DCMAKE_CXX_COMPILER${CR…...

一、Redis五种常用数据类型
Redis优势: 1、性能高—基于内存实现数据的存储 2、丰富的数据类型 5种常用,3种高级 3、原子—redis的所有单个操作都是原子性,即要么成功,要么失败。其多个操作也支持采用事务的方式实现原子性。 Redis特点: 1、支持…...

C语言动态内存管理malloc、calloc、realloc、free函数、内存泄漏、动态内存开辟的位置等的介绍
文章目录 前言一、为什么存在动态内存管理二、动态内存函数的介绍1. malloc函数2. 内存泄漏3. 动态内存开辟位置4. free函数5. calloc 函数6. realloc 函数7. realloc 传空指针 总结 前言 C语言动态内存管理malloc、calloc、realloc、free函数、内存泄漏、动态内存开辟的位置等…...

最近惊爆谷歌裁员
Python团队还没解散完,谷歌又对Flutter、Dart动手了。 什么原因呢,猜测啊。 谷歌裁员Python的具体原因可能是因为公司在进行技术栈的调整和优化。Python作为一种脚本语言,在某些情况下可能无法提供足够的性能或者扩展性,尤其是在…...

音频可视化:原生音频API为前端带来的全新可能!
音频API是一组提供给网页开发者的接口,允许他们直接在浏览器中处理音频内容。这些API使得在不依赖任何外部插件的情况下操作和控制音频成为可能。 Web Audio API 可以进行音频的播放、处理、合成以及分析等操作。借助于这些工具,开发者可以实现自定义的音…...
【中等】保研/考研408机试-动态规划1(01背包、完全背包、多重背包)
背包问题基本上都是模板题,重点:弄熟多重背包模板 dp[j]max(dp[j-v[i]]w[i],dp[j]) //核心思路代码(一维数组版) dp[i][j]max(dp[i-1][j], dp[i-1][j-v[i]]w[i])//二维数字版 一、 0-1背包 一般输入两个变量:体积&…...

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式
一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明:假设每台服务器已…...

19c补丁后oracle属主变化,导致不能识别磁盘组
补丁后服务器重启,数据库再次无法启动 ORA01017: invalid username/password; logon denied Oracle 19c 在打上 19.23 或以上补丁版本后,存在与用户组权限相关的问题。具体表现为,Oracle 实例的运行用户(oracle)和集…...
Ubuntu系统下交叉编译openssl
一、参考资料 OpenSSL&&libcurl库的交叉编译 - hesetone - 博客园 二、准备工作 1. 编译环境 宿主机:Ubuntu 20.04.6 LTSHost:ARM32位交叉编译器:arm-linux-gnueabihf-gcc-11.1.0 2. 设置交叉编译工具链 在交叉编译之前&#x…...
【Linux】C语言执行shell指令
在C语言中执行Shell指令 在C语言中,有几种方法可以执行Shell指令: 1. 使用system()函数 这是最简单的方法,包含在stdlib.h头文件中: #include <stdlib.h>int main() {system("ls -l"); // 执行ls -l命令retu…...

3.3.1_1 检错编码(奇偶校验码)
从这节课开始,我们会探讨数据链路层的差错控制功能,差错控制功能的主要目标是要发现并且解决一个帧内部的位错误,我们需要使用特殊的编码技术去发现帧内部的位错误,当我们发现位错误之后,通常来说有两种解决方案。第一…...

Day131 | 灵神 | 回溯算法 | 子集型 子集
Day131 | 灵神 | 回溯算法 | 子集型 子集 78.子集 78. 子集 - 力扣(LeetCode) 思路: 笔者写过很多次这道题了,不想写题解了,大家看灵神讲解吧 回溯算法套路①子集型回溯【基础算法精讲 14】_哔哩哔哩_bilibili 完…...
linux 错误码总结
1,错误码的概念与作用 在Linux系统中,错误码是系统调用或库函数在执行失败时返回的特定数值,用于指示具体的错误类型。这些错误码通过全局变量errno来存储和传递,errno由操作系统维护,保存最近一次发生的错误信息。值得注意的是,errno的值在每次系统调用或函数调用失败时…...

【2025年】解决Burpsuite抓不到https包的问题
环境:windows11 burpsuite:2025.5 在抓取https网站时,burpsuite抓取不到https数据包,只显示: 解决该问题只需如下三个步骤: 1、浏览器中访问 http://burp 2、下载 CA certificate 证书 3、在设置--隐私与安全--…...

2025盘古石杯决赛【手机取证】
前言 第三届盘古石杯国际电子数据取证大赛决赛 最后一题没有解出来,实在找不到,希望有大佬教一下我。 还有就会议时间,我感觉不是图片时间,因为在电脑看到是其他时间用老会议系统开的会。 手机取证 1、分析鸿蒙手机检材&#x…...
PostgreSQL——环境搭建
一、Linux # 安装 PostgreSQL 15 仓库 sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-$(rpm -E %{rhel})-x86_64/pgdg-redhat-repo-latest.noarch.rpm# 安装之前先确认是否已经存在PostgreSQL rpm -qa | grep postgres# 如果存在࿰…...