AI嵌入式K210项目(23)-人脸检测

文章目录

  • 前言
  • 一、实验准备
  • 二、实验步骤
  • 总结


前言

本章使用预训练好的模型,进行人脸检测,将摄像头采集的画面分析,比对模型,如果有人脸则框出来,并打印相关信息。

一、实验准备

请先将模型文件导入内存卡上,再将内存卡插入到K210开发板的内存卡插槽上,具体操作步骤请参考:
AI嵌入式K210项目(21)-AI模型文件导入至TF卡

本实验使用/sd/KPU/yolo_face_detect/face_detect_320x240.kmodel模型;

人脸检测需要用的内存卡加载模型文件,所以需要提前将模型文件导入内存卡,再将内存卡插入K210开发板的内存卡卡槽里,如果无法读取到内存卡里的模型文件,则会报错。

二、实验步骤

为了方便学习,我们将代码功能分块进行注释;

导入相关库,并初始化摄像头和LCD显示屏

import sensor, image, time, lcd

from maix import KPU
import gc

lcd.init()
# sensor.reset(freq=48000000, dual_buff=True) # improve fps
sensor.reset()                      # Reset and initialize the sensor. It will
                                    # run automatically, call sensor.run(0) to stop
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA)   # Set frame size to QVGA (320x240)
sensor.skip_frames(time = 1000)     # Wait for settings take effect.
clock = time.clock()                # Create a clock object to track the FPS.

初始化KPU相关的参数,kpu需要加载kmodel文件,本次实验需要的模型文件路径为:/sd/KPU/yolo_face_detect/face_detect_320x240.kmodel,并使用yolo2来计算是否符合模型要求。目前检测人脸的阈值为threshold=0.5,如果需要检测人脸更加准确,可以适当调整阈值。

anchor = (0.1075, 0.126875, 0.126875, 0.175, 0.1465625, 0.2246875, 0.1953125, 0.25375, 0.2440625, 0.351875, 0.341875, 0.4721875, 0.5078125, 0.6696875, 0.8984375, 1.099687, 2.129062, 2.425937)
kpu = KPU()
kpu.load_kmodel("/sd/KPU/yolo_face_detect/face_detect_320x240.kmodel")
kpu.init_yolo2(anchor, anchor_num=9, img_w=320, img_h=240, net_w=320 , net_h=240 ,layer_w=10 ,layer_h=8, threshold=0.5, nms_value=0.2, classes=1)

新建while循环,将图像传入KPU进行计算,使用yolo2神经网络算法进行解算,最终得到人脸的位置信息,再将人脸框出来。

while True:
    #print("mem free:",gc.mem_free())
    clock.tick()                    # Update the FPS clock.
    img = sensor.snapshot()
    kpu.run_with_output(img)
    dect = kpu.regionlayer_yolo2()
    fps = clock.fps()
    if len(dect) > 0:
        print("dect:",dect)
        for l in dect :
            a = img.draw_rectangle(l[0],l[1],l[2],l[3], color=(0, 255, 0))

    a = img.draw_string(0, 0, "%2.1ffps" %(fps), color=(0, 60, 128), scale=2.0)
    lcd.display(img)
    gc.collect()

kpu.deinit()

将K210开发板通过TYPE-C数据线连接到电脑上,CanMV IDE点击连接按钮,连接完成后点击运行按钮,运行例程代码。也可以将代码作为main.py下载到K210开发板上运行。
在这里插入图片描述
等待系统初始化完成后,LCD显示摄像头画面,用摄像头拍摄人脸,当检测到人脸后,屏幕会出现绿框把人脸框出来,并且在IDE底部的串行终端打印检测到的人脸的信息。

AI嵌入式K210项目(23)-人脸检测_第1张图片
串口日志如下:
AI嵌入式K210项目(23)-人脸检测_第2张图片


总结

本实验使用K210的KPU和yolov2模型实现人脸检测功能,使用IDE示例中代码,对实现的功能模块加以分析;

你可能感兴趣的:(K210开发板,人工智能,嵌入式AI,AI,嵌入式,K210,人脸检测,KPU)