onnx opencv dnn口罩分类

目录

安装onnxsim

onnx口罩分类 softmax python版:


安装onnxsim

安装onnxsim并不是pip install onnxsim, 这样会报错

正确的安装方式:

step1、安装onnxsim包

pip install onnx-simplifier

step2、加载onnx文件,simplify处理后重新保存,代码如下:

from onnxsim import simplify
onnx_model = onnx.load(output_path)  # load onnx model
model_simp, check = simplify(onnx_model)
assert check, "Simplified ONNX model could not be validated"
onnx.save(model_simp, output_path)
print('finished exporting onnx')



原文链接:https://blog.csdn.net/qq_35037684/article/details/121248694

onnx口罩分类 softmax python版:

# -*- coding: utf-8 -*-
import os
import time

import cv2
import numpy as np

net = cv2.dnn.readNetFromONNX(r'mobile_mask.onnx')
print("net load")


def softmax(x, axis=1):
    # 计算每行的最大值
    row_max = x.max(axis=axis)

    # 每行元素都需要减去对应的最大值,否则求exp(x)会溢出,导致inf情况
    row_max = row_max.reshape(-1, 1)
    x = x - row_max

    x_exp = np.exp(x)
    x_sum = np.sum(x_exp, axis=axis, keepdims=True)
    s = x_exp / x_sum
    return s

if __name__ == '__main__':

    list_path=r"D:\project\face\face_mask\2020\0/"
    list_path = r"test/"

    g = os.walk(list_path)
    files = ['%s\\%s' % (i[0], j) for i in g for j in i[-1] if
             j.endswith('jpg')]

    count=0
    ok_count=0
    for file in files:
        file_path=file
        img=cv2.imread(file)
        if img is None:
            continue
        im_width = 224
        im_height = 224
        # frame = cv2.resize(img, (im_width, im_height))
        start=time.time()

        blob = cv2.dnn.blobFromImage(img, scalefactor=1/255, size=(im_width, im_width), mean=(0, 0, 0),
                                     swapRB=True, crop=False)

        net.setInput(blob)

        heatmap = net.forward(['output0'])

        match = softmax(heatmap[0])
        index = np.argmax(match[0])
        score=match[0][index]
        # index = 0 if match[0] > 0.5 else 1
        id = int(os.path.basename(os.path.dirname(file_path)))
        if id != index:
            count+=1
            print('error',time.time()-start,len(files),ok_count,count, file_path, id, index)
        else:
            ok_count+=1
            print('ok', len(files), ok_count, count,time.time()-start,score)

torch logsoftmax版 

import os
import time
import numpy as np
import cv2
import torch.nn.functional as m_func
import numpy as np
# net = cv2.dnn.readNetFromONNX('../pelee_detector.onnx')
# net = cv2.dnn.readNetFromONNX('FaceBox.onnx')
import torch

net = cv2.dnn.readNetFromONNX(r'mobile_mask.onnx')
print("net load")
import torch.nn.functional as m_func
def detect(file_path,img, height, width, threshold=0.5):
    begin = time.time()

    blob = cv2.dnn.blobFromImage(img, scalefactor=0.003922, size=(width, height), mean=(0, 0, 0),
                                 swapRB=False, crop=False)

    # cv2.dnn.blobFromImage(img, 0.007843, (width, height), 255)
    # blob = blob / 255
    net.setInput(blob)


    # heatmap, scale = self.net.forward(["537", "538", "539", '540'])
    heatmap = net.forward(['output0'])

    # match = m_func.log_softmax(torch.from_numpy(heatmap), dim=1)

    index = np.argmax(heatmap)
    # print(match, "=======", img_arr.shape)


    index= 0 if heatmap[0][0][index] > 0.5 else 1
    id = int(os.path.basename(os.path.dirname(file_path)))
    if id !=index:
        print('time',time.time()-begin,file_path,id,index, heatmap[0][0][index])

if __name__ == '__main__':

    list_path=r"D:\project\face\face_mask\2020\0/"
    list_path = r"test\0/"
    files=os.listdir(list_path)

    count=0
    ok_count=0
    for file in files:
        file_path=list_path+file
        img=cv2.imread(list_path+file)
        if img is None:
            continue
        im_width = 224
        im_height = 224
        # frame = cv2.resize(img, (im_width, im_height))
        start=time.time()

        blob = cv2.dnn.blobFromImage(img, scalefactor=1/255, size=(im_width, im_width), mean=(0, 0, 0),
                                     swapRB=True, crop=False)

        # cv2.dnn.blobFromImage(img, 0.007843, (width, height), 255)
        net.setInput(blob)

        # heatmap, scale = self.net.forward(["537", "538", "539", '540'])
        heatmap = net.forward(['output0'])

        match = m_func.log_softmax(torch.from_numpy( heatmap[0][0]),dim=0).data.numpy()

        index = np.argmax(match)

        # index = 0 if match[0] > 0.5 else 1
        id = int(os.path.basename(os.path.dirname(file_path)))
        if id != index:
            count+=1
            print('time',time.time()-start,len(files),ok_count,count, file_path, id, index, match)
        else:
            ok_count+=1
            print('ok', len(files), ok_count, count,time.time()-start)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AI算法网奇

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

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

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

打赏作者

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

抵扣说明:

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

余额充值