python算法部署(通信篇)

news2024/7/4 23:50:06

1.docker+flask方式

# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
"""
Run a Flask REST API exposing one or more YOLOv5s models
"""


import argparse
import io
import json


import torch
from flask import Flask, jsonify, request,Response
from PIL import Image
import numpy as np
import cv2
import requests 
from collections import OrderedDict
import os

app = Flask(__name__)
models = {}

DETECTION_URL = '/v1/object-detection/<model>'

@app.route(DETECTION_URL, methods=['POST'])
# @app.route(DETECTION_URL, methods=['GET'])

def predict(model):

    if request.method != 'POST':
    # if request.method != 'GET':
        
        return jsonify({'error':'Invalid request method'})
    print(request.data)
    
    if request.data:
        try:
            # img = np.frombuffer(request.data,dtype=np.uint8)#转成np矩阵
            img = cv2.imdecode(np.frombuffer(request.data,dtype=np.uint8),cv2.IMREAD_COLOR) 
            if img is None:
                raise Exception("Invalid image data")
        except Exception as e:
            # print(f"An error occurred: {str(e)}")
            
            return jsonify({'error':'Invalid image data'})
        if model in models:
            # results = models[model](img, size=640)  # reduce size=320 for faster inference
            results = models[model](img)  # reduce size=320 for faster inference
            # return results.pandas().xyxy[0].to_json(orient='records')
            detection_results = []
            for detection in results.pandas().xyxy[0].to_dict(orient='records'):
                detection_result = {
                    "name": detection["name"],
                    "score": float(detection["confidence"]),
                    "bbox": [
                        float(detection["xmin"]),
                        float(detection["ymin"]),
                        detection["xmax"] - detection["xmin"],
                        detection["ymax"] - detection["ymin"]
                    ]
                }
                detection_results.append(detection_result)
            response_data = OrderedDict()
            response_data["imgUrl"] = img
            response_data["imgSize"] = [img.shape[1], img.shape[0]]
            response_data["code"] = 0
            response_data["msg"] = ""   
            response_data["objects"] = detection_results
            
            return Response(json.dumps(response_data), mimetype='application/json')


    if request.files.get('image'):
        # Method 1
        # with request.files["image"] as f:
        #     im = Image.open(io.BytesIO(f.read()))

        # Method 2
        im_file = request.files['image']
        im_filename = os.path.join(os.path.dirname(__file__),im_file.filename)
        im_bytes = im_file.read()
        try:
            im = Image.open(io.BytesIO(im_bytes))

        except Exception as e:
            response_data = OrderedDict()
            response_data["imgUrl"] = ""
            response_data["imgSize"] = [0,0]
            response_data["code"] = 1
            response_data["msg"] = ""  
            response_data["objects"] = []
            response_data["error"] = 'Invalid image file'

            return Response(json.dumps(response_data), mimetype='application/json')
        
        # if model in models:
        #     results = models[model](im, size=640)  # reduce size=320 for faster inference
        #     # return results.pandas().xyxy[0].to_json(orient='records')
        #     detection_results = []
        #     for detection in results.pandas().xyxy[0].to_dict(orient='records'):
        #         detection_result = {
        #             "name": detection["name"],
        #             "score": float(detection["confidence"]),
        #             "bbox": [
        #                 float(detection["xmin"]),
        #                 float(detection["ymin"]),
        #                 detection["xmax"] - detection["xmin"],
        #                 detection["ymax"] - detection["ymin"]
        #             ]
        #         }
        #         detection_results.append(detection_result)

        #     response_data = OrderedDict()
        #     response_data["imagePath"] = im_filename
        #     response_data["imageSize"] = [im.width, im.height]
        #     response_data["code"] = 0
        #     response_data["msg"] = ""   
        #     response_data["objects"] = detection_results
            
        #     return Response(json.dumps(response_data), mimetype='application/json')


    if request.form.get('image_url'):
        image_url = request.form.get('image_url')
        try:
            response = requests.get(image_url)
            im = Image.open(io.BytesIO(response.content))
        except Exception as e:
            return jsonify({'error':'Failed to download or open image from URL'})
        if model in models:
            results = models[model](im, size=640)  # reduce size=320 for faster inference
            # return results.pandas().xyxy[0].to_json(orient='records')
            detection_results = []
            for detection in results.pandas().xyxy[0].to_dict(orient='records'):
                detection_result = OrderedDict()
                detection_result = {
                    "name": detection["name"],
                    "score": float(detection["confidence"]),
                    "bbox": [
                        float(detection["xmin"]),
                        float(detection["ymin"]),
                        detection["xmax"] - detection["xmin"],
                        detection["ymax"] - detection["ymin"]
                    ]
                }
                detection_results.append(detection_result)

            response_data = OrderedDict()
            response_data["imgUrl"] = image_url
            response_data["imgSize"] = [im.width, im.height]
            response_data["code"] = 0  
            response_data["msg"] = "" 
            response_data["objects"] = detection_results
            return Response(json.dumps(response_data), mimetype='application/json')
        
    response_data = OrderedDict()
    response_data["imgUrl"] = ""
    response_data["imgSize"] = [0,0]
    response_data["code"] = 1
    response_data["msg"] = ""  
    response_data["objects"] = []
    response_data["error"] = 'No image file or URL or model found'

    return Response(json.dumps(response_data), mimetype='application/json')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Flask API exposing YOLOv5 model')
    parser.add_argument('--port', default=8008, type=int, help='port number')
    parser.add_argument('--model', nargs='+', default=['yolov5s'], help='model(s) to run, i.e. --model yolov5n yolov5s')
    opt = parser.parse_args()

    for m in opt.model:
        # models[m] = torch.hub.load('ultralytics/yolov5', m, force_reload=True, skip_validation=True)
        # models[m] = torch.hub.load('./', m, source="local")WWWWWW
        # models[m] = torch.hub.load('./', 'custom', path='/data1/hzb/yolov5/animals-80.pt', source="local")
        models[m] = torch.hub.load('./', 'custom', path='/data1/hzb/yolov5/zs_animals.pt', source="local")
    app.run(host='0.0.0.0', port=opt.port)  # debug=True causes Restarting with stat

2.lcm方式

详细教程可以参考官网:(写的很清楚),各种语言

http://lcm-proj.github.io/lcm/

lcm只能是组播地址
默认使用的通信方式:

LCM (std::string lcm_url="")
1
参数的含义是一个url,一般使用默认,这个url写了ip地址和端口号,我们查看一下lcm默认的地址:

"udpm://239.255.76.67:7667?ttl=1"

如果要使用多机通信
参考下面链接

https://blog.csdn.net/weixin_45467056/article/details/123569027

在 Windows 上还需要关闭防火墙,成功 ping 通后,在 Ubuntu 环境中首先需要运行ifconfig | grep -B 1 | grep “flags”| cut -d ‘:’ -f1,查看该 IP 对应的网络设备,其中 需要用实际获取到的 IP 地址进行替换。

假设我们对应的网络设备是 lo,下面用 代替,使用时需要进行替换。运行下面两条命令来显式使能 UDP 多播和添加路由表。
在这里插入图片描述
Ubuntu 配置结束,可以正常进行消息的收发。

2.tornado方式

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

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

相关文章

公司新来的实习生问我SpringBoot多个环境的配置方式

这是一篇写给新手的文章&#xff0c;老手可以绕行了。 起因是一个同学让我帮他看个问题&#xff0c;他说有两个环境&#xff0c;一个环境有问题&#xff0c;另一个环境没问题&#xff0c;但是一直找不到原因&#xff0c;假设一个环境是 dev&#xff0c;另一个环境是 test。 于…

2023 版 QQ 机器人运行部署文档

文章目录 1.前置说明2.机器人框架的下载与运行2.1 下载机器人框架2.2 下载可操作框架的静态页面2.3 运行机器人框架 3.登录QQ机器人3.1 前提说明3.2 扫码登录3.3 注意事项 4.后端程序处理消息4.1 下载 stater4.2 stater 基本说明4.3 运行后端程序4.4 测试消息处理4.5 关于扩展消…

ISE_ChipScope Pro的使用

1.ChipScope Pro Core Inserter 使用流程 在之前以及编译好的流水灯实验上进行学习 ChipScope的使用。 一、新建一个ChipScope 核 点击Next,然后在下一个框中选择 Finish&#xff0c;你就会在项目菜单中看到有XX.cdc核文件。 二、对核文件进行设置 右键“Synthesize – XST” …

计算机丢失ac1st16.dll怎么解决?教你简单的修复ac1st16.dl文件

在使用Windows操作系统时&#xff0c;有时会遇到一些DLL文件丢失的问题&#xff0c;其中之一就是AC1ST16.DLL。AC1ST16.DLL是用于AutoCAD相关软件的动态链接库文件&#xff0c;当该文件丢失时&#xff0c;可能会导致软件无法正常运行。本文将详细介绍多种解决AC1ST16.DLL丢失问…

OpenGL超级宝典(第五版)第8章fbo_drawbuffers例子分析

目录 1. 概述 2. 疑难点剖析 2.1 SetupRC函数分析 2.2 multibuffer.vs分析 2.3 RenderScene分析 3. 其它 1. 概述 《OpenGL超级宝典(第五版&#xff09;》如下&#xff1a; 该书第8版的 fbo_drawbuffers工程展示了如下技术点&#xff1a; 什么是帧缓冲区对象&#xff08…

【Linux】进程间通信方式②——文件共享映射(附图解与代码实现)

我们来简单了解下文件共享映射的定义&#xff1a;通过映射文件&#xff0c;使用映射机制&#xff0c;实现资源共享&#xff0c;完成进程通信 具体是如何实现的呢&#xff1f;跟随着这篇博客&#xff0c;我们来看一看 进程通过文件共享映射实现通信的具体步骤 由某一进程创建映…

【湖科大教书匠】计算机网络随堂笔记第2章(计算机网络物理层)

目录 2.1、物理层的基本概念 2.2、物理层下面的传输媒体 导引型传输媒体 同轴电缆 双绞线 光纤 电力线 非导引型传输媒体 无线电波 微波 红外线 可见光 2.3、传输方式 串行传输和并行传输 同步传输和异步传输 单向通信&#xff08;单工&#xff09;、双向交替通信&#xf…

【LeetCode-简单题】110. 平衡二叉树

文章目录 题目方法一&#xff1a;后序递归 题目 方法一&#xff1a;后序递归 递归遍历的同时判断是否是平衡二叉树&#xff0c;如果不是&#xff0c;就置为-1&#xff0c;如果是 就正常做递归求最大深度 参考图解网址 判断平衡二叉树 class Solution {public boolean isBalanc…

誉天在线项目-放大招-Vue3集成RichText富文本客户端组件QuillEditor

背景 开发中我们需要填写图文内容&#xff0c;就是含有图片和文字&#xff0c;html标准组件中是没有的。都是第三方来实现&#xff0c;就需要我们去集成。 有早期的fckEditor、ckEditor等&#xff0c;新的我们使用了vue框架&#xff0c;市场又推出了quillEditor。下面我们就在…

【【萌新的SOC学习之绪论】】

萌新的SOC学习之绪论 Vitis 统一软件平台的前身为 Xilinx SDK&#xff0c;从 Vivado 2019.2 版本开始&#xff0c;Xilinx SDK 开发环境已统一整合 到全功能一体化的 Vitis 中。Vitis 开发平台除了启动方式、软件界面、使用方法与 SDK 开发平台略有区别&#xff0c; 其他操作几…

使用acme.sh申请免费ssl证书(Cloudflare方式API自动验证增加DNS Record到期证书到期自动重新申请)

下载acme.sh curl https://get.acme.sh | sh -s emailmyexample.comcd ~/.acme.sh/获取Cloudflare密钥 Preferences | Cloudflare 登录选择账户详情选择API Token选择创建令牌选择区域DNS模板&#xff0c;并设置编辑写入权限生成并复制令牌备用回到首页概览界面下部获取账号…

【RabbitMQ实战】3分钟在Linux上安装RabbitMQ

本节采用docker安装RabbitMQ。采用的是bitnami的镜像。Bitnami是一个提供各种流行应用的Docker镜像和软件包的公司。采用docker的方式3分钟就可以把我们想安装的程序运行起来&#xff0c;不得不说真的很方便啊&#xff0c;好了&#xff0c;开搞。使用前提&#xff1a;Linux虚拟…

3D设计软件Rhinoceros 6 mac 犀牛6中文版功能特征

Rhinoceros Mac中文版是一款3D设计软件“犀牛”&#xff0c;在众多三维建模软件中&#xff0c;Rhinoceros mac因为其体积小、功能强大、对硬件要求低而广受欢迎&#xff0c;对于专业的3D设计人员来说它是一款非常不错的3D建模软件&#xff0c;Rhinoceros Mac中文版能轻易整合3D…

苹果手机短信删除了怎么恢复?3种有效方法介绍

手机短信是一种即时通信方式&#xff0c;人们可以使用短信来达到快速传递信息的目的。在没有网络或者网络不稳定的时候&#xff0c;短信仍然可以做到发送和接收&#xff0c;这弥补了其他网络通信软件的缺点。 所以说&#xff0c;手机短信仍然是我们生活中不可缺少的一部分。当…

【rtp】mid 扩展: RtpMid 字符串扩展的解析和写入

mid 是uint8_t 类型? 扩展填写的是字符串,读取字符串后atoi 转 uint8_t : webrtc 看起来是个字符串:写入 扩展的值是改变了: 这里是更新扩展的长度: 新的大小小于原来的,没有缩减内存,而是对于多余的置位0了:if (len < current_len) {memset(

基于SSM的高校图书馆个性化服务的设计与实现(有报告)。Javaee项目。

演示视频&#xff1a; 基于SSM的高校图书馆个性化服务的设计与实现&#xff08;有报告&#xff09;。Javaee项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层体系结构&#xff0c;通过S…

如何在低代码平台中应用可视化编程

可视化编程&#xff0c;亦即可视化程序设计&#xff1a;以“所见即所得”的编程思想为原则&#xff0c;力图实现编程工作的可视化&#xff0c;即随时可以看到结果&#xff0c;程序与结果的调整同步。可视化编程的理念来源于可视化技术&#xff0c;它指的是一种把计算机程序中的…

深度学习在视频直播美颜sdk中的应用

视频直播美颜SDK是一类用于实时视频美颜处理的工具包&#xff0c;它们利用深度学习算法来提高视频直播中的主播和观众的外观吸引力。本文将深入探讨深度学习在视频直播美颜sdk中的应用&#xff0c;以及这些应用对直播行业的重要性。 一、人脸检测与关键点定位 通过卷积神经网…

Centos7安装go解释器

Centos7安装go解释器 下载解压go压缩包编辑go变量结果验证 下载解压go压缩包 # 下载 wget -c https://go.dev/dl/go1.20.2.linux-amd64.tar.gz# 解压到指定目录 tar xvf go1.20.2.linux-amd64.tar.gz -C /usr/local/编辑go变量 /etc/profile.d/go.sh # 指定go执行程序位置 e…

多线程进阶:常见的锁策略、CAS

之前我们所了解的属于多线程的初阶内容。今天开始&#xff0c;我们进入多线程进阶的学习。 锁的策略 乐观锁 悲观锁 这不是两把具体的锁&#xff0c;应该叫做“两类锁” 乐观锁&#xff1a;预测锁竞争不是很激烈&#xff08;这里做的工作可能就会少一些&#xff09; 悲观锁…