AI算法例程=maixpy3

一、边缘检测sobel算子系列

运行条件

  • 确认 MaixPy3 版本为 0.4.3 以上
  • 使用的硬件为 MaixII-Dock
  • 内存卡内是最新版本的镜像系统
  • 插卡启动硬件

部署到MaixII-Dock上

  • 在MaixHub上获取模型文件核运行源码

在这里插入图片描述

# 边缘提取类定义
global Edge
class Edge:
    model = {
        "param": "/home/model/sobel_int8.param",
        "bin": "/home/model/sobel_int8.bin"
    }
    input_size = (224, 224, 3)
    output_size = (222, 222, 3)
    options = {
        "model_type":  "awnn",
        "inputs": {
            "input0": input_size
        },
        "outputs": {
            "output0": output_size
        },
        "mean": [127.5, 127.5, 127.5],
        "norm": [0.0078125, 0.0078125, 0.0078125],
    }
    def __init__(self):
        from maix import nn
        print("-- load model:", self.model)
        self.model = nn.load(self.model, opt=self.options)
        print("-- load ok")
    def __del__(self):
        del self.model
print(Edge)

# 开始进行边缘检测
from maix import camera,display
import numpy as np
import time
m=Edge()#实例化对象
while True:
	img=camera.capture().resize(224,224)
	time_start=time.time()
	out=m.model.forward(img,quantize=True,layout="hwc")#模型推理
	while True:
    img = camera.capture().resize(224,224)
    out = m.model.forward(img, quantize=True, layout="hwc")
    out = out.astype(np.float32).reshape(m.output_size)
    out = (np.ndarray.__abs__(out) * 255 / out.max()).astype(np.uint8)
    data = out.tobytes()
    img2 = img.load(data,(222, 222), mode="RGB")
    display.show(img2)

二、物品分类resnet18

运行条件

  • 确认 MaixPy3 版本为 0.4.3 以上
  • 使用的硬件为 MaixII-Dock
  • 内存卡内是最新版本的镜像系统
  • 插卡启动硬件

部署到MaixII-Dock上

  • 在MaixHub上获取模型文件核运行源码

在这里插入图片描述

# 模型分类定义
global Resnet
class Resnet:
    m = {
        "param": "/home/model/resnet18_1000_awnn.param",
        "bin": "/home/model/resnet18_1000_awnn.bin"
    }
    options = {
        "model_type":  "awnn",
        "inputs": {
            "input0": (224, 224, 3)
        },
        "outputs": {
            "output0": (1, 1, 1000)
        },
        "first_layer_conv_no_pad": False,
        "mean": [127.5, 127.5, 127.5],
        "norm": [0.00784313725490196, 0.00784313725490196, 0.00784313725490196],
    }
    def __init__(self):
        from maix import nn
        self.model = nn.load(self.m, opt=self.options)
    def __del__(self):
        del self.model
print(Resnet)

# 分类识别,运行神经网络
import os
os.chdir("/home/res/") # checkout work dir
from classes_label import labels 
from maix import camera, nn, display
resnet = Resnet()
print(resnet.model)
while True:
    img = camera.capture().resize(224, 224)
    out = resnet.model.forward(img, quantize=True)
    msg = "{:.2f}: {}".format(out.max(), labels[out.argmax()])
    img.draw_string(0, 0, str(msg), 1, (0, 0, 255), 1)
    display.show(img)

三、目标检测yolov2==单标签

运行条件

  • 确认 MaixPy3 版本为 0.4.3 以上
  • 使用的硬件为 MaixII-Dock
  • 内存卡内是最新版本的镜像系统
  • 插卡启动硬件

部署到MaixII-Dock上

  • 在MaixHub上获取模型文件核运行源码

在这里插入图片描述

# 部署人脸目标检测网络模型
global Yolo
class Yolo:
    labels = ["person"]
    anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
    m = {
        "param": "/home/model/face/yolo2_face_awnn.param",
        "bin": "/home/model/face/yolo2_face_awnn.bin"
    }
    options = {
        "model_type":  "awnn",
        "inputs": {
            "input0": (224, 224, 3)
        },
        "outputs": {
            "output0": (7, 7, (1+4+len(labels))*5)
        },
        "mean": [127.5, 127.5, 127.5],
        "norm": [0.0078125, 0.0078125, 0.0078125],
    }
    def __init__(self):
        from maix import nn
        from maix.nn import decoder
        self.model = nn.load(self.m, opt=self.options)
        self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
    def __del__(self):
        del self.model
        del self.decoder
print(Yolo)

# 分类识别,运行神经网络
from maix import camera, display
yolo = Yolo()
print(yolo)
while True:
    img = camera.capture().resize(224, 224)
    out = yolo.model.forward(img, quantize=True, layout="hwc")
    boxes, probs = yolo.decoder.run(out, nms=0.3, threshold=0.5, img_size=(224, 224))
    if len(boxes):
        for i, box in enumerate(boxes):
            img.draw_rectangle(box[0], box[1], box[0]+box[2], box[1]+box[3], (255,0,0), 1)
        display.show(img)
    else:
        display.show(img)

四、数字识别=多标签+标框

运行条件

  • 在 MaixHub 上获取模型文件,并将模型文件存放到 U 盘中
  • 确认 MaixPy3 版本为 0.4.3 以上
  • 使用的硬件为 MaixII-Dock
  • 内存卡内是最新版本的镜像系统
  • 插卡启动硬件

部署到MaixII-Dock上

# 将模型读取到python环境中!
global Number_recognition
class Number_recognition:
    labels = ["1", "2", "3", "4", "5", "6", "7", "8"]
    anchors = [2.44, 2.25, 5.03, 4.91, 3.5 , 3.53, 4.16, 3.94, 2.97, 2.84]
    model = {
        "param": "/root/number_awnn.param",
        "bin": "/root/number_awnn.bin"
    }
    options = {
        "model_type":  "awnn",
        "inputs": {
            "input0": (224, 224, 3)
        },
        "outputs": {
            "output0": (7, 7, (1+4+len(labels))*5)
        },
        "mean": [127.5, 127.5, 127.5],
        "norm": [0.0078125, 0.0078125, 0.0078125],
    }
    w = options["inputs"]["input0"][1]
    h = options["inputs"]["input0"][0]
    def __init__(self):
        from maix import nn
        from maix.nn import decoder
        self.m = nn.load(self.model, opt=self.options)
        self.yolo2_decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(self.w, self.h), net_out_size=(7, 7))
    def map_face(self, box):                           #将224*224空间的位置转换到240*240空间内
        def tran(x):
            return int(x/224*240)
        box = list(map(tran, box))
        return box
print(Number_recognition)

# 数字识别
ffrom maix import camera, display, image
number_recognition = Number_recognition()
while True:
    img = camera.capture()
    AI_img = img.copy().resize(224, 224)
    out = number_recognition.m.forward(AI_img.tobytes(), quantize=True, layout="hwc")
    boxes, probs = number_recognition.yolo2_decoder.run(out, nms=0.3, threshold=0.5, img_size=(240, 240))
    for i, box in enumerate(boxes):
        class_id = probs[i][0]
        prob = probs[i][1][class_id]
        disp_str = "{}:{:.2f}%".format(number_recognition.labels[class_id], prob*100)
        font_wh = image.get_string_size(disp_str)
        box = number_recognition.map_face(box)
        img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3], color = (255, 0, 0), thickness=2)
        img.draw_rectangle(box[0], box[1] - font_wh[1], box[0] + font_wh[0], box[1], color= (255, 0, 0))
        img.draw_string(box[0], box[1] - font_wh[1], disp_str, color= (255, 0, 0))
    display.show(img)

五、在线学习,图像分类

运行条件

  • 在 MaixHub 上获取模型文件,并将模型文件存放到 U 盘中
  • 确认 MaixPy3 版本为 0.4.3 以上
  • 使用的硬件为 MaixII-Dock
  • 内存卡内是最新版本的镜像系统
  • 插卡启动硬件

部署到MaixII-Dock上
在这里插入图片描述

1、将模型读取搭配python环境中

from maix import nn
from maix import camera, display
import time

global Self_learn
class Self_learn:
    model = {
        "param": "/home/model/resnet18_1000_awnn.param",
        "bin": "/home/model/resnet18_1000_awnn.bin"
    }
    options = {
        "model_type":  "awnn",
        "inputs": {
            "input0": (224, 224, 3)
        },
        "outputs": {
            "190": (1, 1, 512)
        },
        "mean": [127.5, 127.5, 127.5],
        "norm": [0.0176, 0.0176, 0.0176],
    }
    class_num = 3  #学习类别
    sample_num = 15  #学习类别总数量
    curr_class = 0
    curr_sample = 0    
    def __init__(self):
        from maix import nn
        from maix.nn.app.classifier import Classifier
        print("-- load model:", self.model)
        self.m = nn.load(self.model, opt=self.options)
        print("-- load ok")
        print("-- load classifier")
        self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224)
        print("-- load ok")

2、添加分类的类别

  • 通过摄像头拍摄物体2秒来进行添加,当画面卡住不动的时候,就需要移动到下一个类别等待摄像头启动,进行添加
  • 以下代码只能添加3个类别,模型是没有上限
import time
from maix import camera, display
global self_learn

self_learn = Self_learn()
for x in range(3):
    t = time.time()
    while True:
        if (time.time() - t) > 2:
            img = camera.capture().resize(224, 224)
            self_learn.classifier.add_class_img(img)
            display.show(img)
            time.sleep(2)
            print("add ok!")
            break
        img = camera.capture()
        display.show(img)

3、制作模型训练的数据集

import time
from maix import nn
from maix import camera, display

for x in range(3):
    t = time.time()
    while True:
        if (time.time() - t) > 2:
            for i in range(5):
                img = camera.capture().resize(224, 224)
                self_learn.classifier.add_sample_img(img)
                display.show(img)
            time.sleep(2)
            break
        display.show(camera.capture())

4、进行图片自学习

self_learn.classifier.train()
print("train over")

5、训练结束后保存模型

self_learn.classifier.save("./module.bin")
print("save over")

6、开始分类验证

import time
from maix import nn
from maix import camera, display
while True:
    img = camera.capture()
    AI_img = img.copy().resize(224, 224)
    idx, distance = self_learn.classifier.predict(AI_img)
    msg = "predict class: " + str(idx+1) + ", conf: " + str(100-distance)
    print(msg)
    img.draw_string(10, 10, msg, color = (255, 0, 0))  
    display.show(img)

7、读取自学习模型

global Self_learn
class Self_learn:
    model = {
        "param": "/home/model/resnet18_1000_awnn.param",
        "bin": "/home/model/resnet18_1000_awnn.bin"
    }
    options = {
        "model_type":  "awnn",
        "inputs": {
            "input0": (224, 224, 3)
        },
        "outputs": {
            "190": (1, 1, 512)
        },
        "mean": [127.5, 127.5, 127.5],
        "norm": [0.0176, 0.0176, 0.0176],
    }
    class_num = 3  #学习类别
    sample_num = 15  #学习类别总数量
    curr_class = 0
    curr_sample = 0    
    def __init__(self):
        from maix import nn
        from maix.nn.app.classifier import Classifier
        from maix.nn.app.classifier import load
        import os.path
        if os.path.isfile("./module.bin"):
            print("-- load model:", self.model)
            self.m = nn.load(self.model, opt=self.options)
            print("-- load ok")
            print("-- load classifier")
            self.classifier = load(self.m,"./module.bin")
            print("-- load ok")
        else:
            print("not have model!")
            print("please run nn_self_learn_classifier.py get model!")
print(Self_learn)

8、自学习预测

import time
from maix import camera, display
global self_learn
self_learn = Self_learn()
while True:
    img = camera.capture()
    AI_img = img.copy().resize(224, 224)
    idx, distance = self_learn.classifier.predict(AI_img)
    msg = "predict class: " + str(idx+1) + ", conf: " + str(100-distance)
    # print(msg)
    img.draw_string(10, 10, msg, color = (255, 0, 0))
    display.show(img)
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

栋哥爱做饭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值