YOLO v5模型中加入mysql数据库,(修改)检测有结果再保存图片

mysql数据库连接工具类

import sys
import time

import pymysql
from dbutils.pooled_db import PooledDB
from pathlib import Path

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH

# 数据库配置模块
class Config(object):
    # DEBUG = True
    # SECRET_KEY = "umsuldfsdflskjdf"
    # PERMANENT_SESSION_LIFETIME = timedelta(minutes=20)
    # SESSION_REFRESH_EACH_REQUEST = True
    # SESSION_TYPE = "redis"
    PYMYSQL_POOL  = PooledDB(
        creator=pymysql,  # 使用链接数据库的模块
        maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
        mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
        maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
        maxshared=3,
        # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
        blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
        maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
        setsession=[],  # 开始会话前执行的命令列表。
        ping=0,
        # ping MySQL服务端,检查是否服务可用。
        host='127.0.0.1',
        port=3306,
        user='root',
        password='123456',
        database='demo',
        charset='utf8'
    )

# 数据库操作类
class SQLHelper(object):
    @staticmethod
    def open(cursor):
        POOL = Config.PYMYSQL_POOL
        conn = POOL.connection()
        cursor = conn.cursor(cursor=cursor)
        return conn, cursor

    @staticmethod
    def close(conn, cursor):
        conn.commit()
        cursor.close()
        conn.close()

    @classmethod
    def fetch_one(cls, sql, args, cursor=pymysql.cursors.DictCursor):
        conn, cursor = cls.open(cursor)
        cursor.execute(sql, args)
        obj = cursor.fetchone()
        cls.close(conn, cursor)
        return obj

    @classmethod
    def fetch_all(cls, sql, args, cursor=pymysql.cursors.DictCursor):
        conn, cursor = cls.open(cursor)
        cursor.execute(sql, args)
        obj = cursor.fetchall()
        cls.close(conn, cursor)
        return obj

# 一次插入操作
# if __name__ == '__main__':
#     # 存入图片
#     with open('test0.jpg', "rb") as f:
#         image = f.read()
#         f.close()
#     nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  # 当前时间
#     obj = SQLHelper.fetch_one("insert into detect(filename,picture,time,result,detector) values(%s,%s,%s,%s,%s)",
#                               args=("test0.jpg", image, nowTime, "yes", "mask"))
#     print(obj)

标题修改YOLO v5 detect.py文件代码

 # 保存检测结果,本地保存图片或者视频
            if save_img:
                if dataset.mode == 'image':
                    sql_result = "no"
                    # 加入检测结果判断逻辑:如果检测有画框,则保存
                    # 避免没检测到的图片仍然存入到exp中占用大量的存储空间(业务逻辑需要)
                    if len(det):
                        cv2.imwrite(save_path, im0)
                        sql_result = "yes"

                    #   存入mysql数据库
                    nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #当前时间
                    obj = SQLHelper.fetch_one("insert into detect(filename,picture,time,result,detector) values(%s,%s,%s,%s,%s)",
                                                  args=(p.name, im0, nowTime, sql_result,"mask"))
  • 4
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
以下是用OpenCV推理Yolo V5模型并输出带矩形检测框的图片的Python代码实现: ```python import cv2 import numpy as np # 加载模型和类别标签 net = cv2.dnn.readNetFromDarknet("yolov5.cfg", "yolov5.weights") classes = [] with open("coco.names", "r") as f: classes = [line.strip() for line in f.readlines()] # 加载图片 img = cv2.imread("test.jpg") # 获取图片尺寸 height, width, channels = img.shape # 创建输入blob并执行前向推理 blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False) net.setInput(blob) outputs = net.forward(net.getUnconnectedOutLayersNames()) # 获取检测框及其置信度和类别 class_ids = [] confidences = [] boxes = [] for output in outputs: for detection in output: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) x = int(center_x - w/2) y = int(center_y - h/2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) # 应用非最大抑制算法 indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # 输出带矩形检测框的图片 for i in indices.flatten(): x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) confidence = str(round(confidences[i], 2)) color = (0, 255, 0) cv2.rectangle(img, (x, y), (x+w, y+h), color, 2) cv2.putText(img, label + " " + confidence, (x, y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) cv2.imwrite("result.jpg", img) ``` 注:在运行以上代码前,请确保已经成功下载了Yolo V5模型文件(yolov5.cfg和yolov5.weights)、类别标签文件(coco.names)以及待检测的图片文件(test.jpg)。另外,需要安装OpenCV库和Numpy库。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值