Embedded_game/002_B_Car/使用模型2.py

79 lines
2.3 KiB
Python
Raw Permalink Normal View History

2025-01-02 12:48:11 +08:00
# Untitled - By: nian0 - 周一 11月 20 2023
import sensor,image,lcd,time
import KPU as kpu
import gc
#摄像头初始化
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_vflip(1) #摄像头后置方式
lcd.init() #LCD初始化
clock = time.clock()
#模型分类按照20class顺序
#classes = ['light']
classes = ['red', 'green', 'yellow', 'light']
# 从SD加载模型卡上。将kmodel文件通过读卡器拷贝到SD卡。
task = kpu.load("/sd/model-95325.kmodel") #模型SD卡上
#网络参数
#anchors = [0.72, 0.88, 0.81, 2.56, 0.91, 1.0, 0.66, 0.72, 1.03, 1.16]
anchor = (1.0, 1.13, 0.75, 0.84, 0.72, 2.41, 1.13, 3.81, 0.88, 2.72)
#初始化yolo2网络识别可信概率为0.770%
a = kpu.init_yolo2(task, 0.7, 0.3, 5, anchor)
while(True):
gc.collect() # 内存回收
clock.tick()
img = sensor.snapshot()
img = img.resize(224, 224)
## 首先获取图像的宽度和高度
#w = img.width()
#h = img.height()
## 计算中心截取区域的左上角坐标
#x = (w - 224) // 2
#y = (h - 224) // 2
## 使用图像对象的 crop 方法进行截取
#img = img.crop((x, y, 224, 224))
#print("sd")
img.save("/sd/example.jpg")
#print("23rwwfd")
img.pix_to_ai() # 将图像数据从标准的像素格式转换为 KPU 可以处理的格式
t = time.ticks_ms()
code = kpu.run_yolo2(task, img) #运行yolo2网络
t = time.ticks_ms() - t
#if code:
#for i in code:
#a=img.draw_rectangle(i.rect())
#a = lcd.display(img)
#print(classes[i.classid()])
#lcd.draw_string(i.x(), i.y(), classes[i.classid()], lcd.RED, lcd.WHITE)
#lcd.draw_string(i.x(), i.y()+12, '%f1.3'%i.value(), lcd.RED, lcd.WHITE)
print(code)
if code:
for obj in code:
pos = obj.rect()
print(classes[obj.classid()])
img.draw_rectangle(pos)
img.draw_string(pos[0], pos[1], "%s : %.2f" %(classes[obj.classid()], obj.value()), scale=2, color=(255, 0, 0))
#comm.send_detect_result(code, classes)
#img.draw_string(0, 200, "t:%dms" %(t), scale=2, color=(255, 0, 0))
a = lcd.display(img)
else:
a = lcd.display(img)
#print(clock.fps())#打印FPS