问题遇到的现象和发生背景
最近在搞一个水果识别的小项目,遇到一些问题,大概就是利用k210进行云端训练,目前已经成功识别出了水果(红苹果),现在想要识别两种苹果,一种是青苹果,一种是红苹果;k210识别之后,分别统计两种苹果的数目(这一点我没有头绪),可以利用串口与上位机通信,获取到两种苹果的数目(比如说打印出来?),问题就是k210那端识别出来该怎么分别计数呢,如何避免对一个苹果重复识别?
求各位给点思路。
下面是k210单单只是识别红苹果的代码,识别绿苹果的我还没有训练
问题相关代码,请勿粘贴截图
generated by maixhub, tested on maixpy3 v0.4.8
copy files to TF card and plug into board and power on
import sensor, image, lcd, time
import KPU as kpu
import gc, sys
input_size = (224, 224)
labels = ['apple']
anchors = [3.28, 4.04, 2.75, 3.56, 4.44, 5.31, 3.16, 4.33, 3.62, 4.29]
def lcd_show_except(e):
import uio
err_str = uio.StringIO()
sys.print_exception(e, err_str)
err_str = err_str.getvalue()
img = image.Image(size=input_size)
img.draw_string(0, 10, err_str, scale=1, color=(0xff,0x00,0x00))
lcd.display(img)
def main(anchors, labels = None, model_addr="/sd/m.kmodel", sensor_window=input_size, lcd_rotation=0, sensor_hmirror=False, sensor_vflip=False):
sensor.reset() #初始化摄像头
sensor.set_pixformat(sensor.RGB565) #设置摄像为RGB565格式
sensor.set_framesize(sensor.QVGA)#分辨率为QVGA,即320x240
sensor.set_windowing(sensor_window)#设置摄像头为224,224
sensor.set_hmirror(sensor_hmirror)#设置摄像头水平镜像 enable 开启水平镜像
sensor.set_vflip(sensor_vflip)# 设置摄像头垂直镜像 表示开启垂直镜像
sensor.run(1)
lcd.init(type=1)
lcd.rotation(lcd_rotation) #反转LCD屏幕
lcd.clear(lcd.WHITE)
if not labels:
with open('labels.txt','r') as f:
exec(f.read())
if not labels:
print("no labels.txt")
img = image.Image(size=(320, 240))
img.draw_string(90, 110, "no labels.txt", color=(255, 0, 0), scale=2)
lcd.display(img)
return 1
try:
img = image.Image("startup.jpg")
lcd.display(img)
except Exception:
img = image.Image(size=(320, 240))
img.draw_string(90, 110, "loading model...", color=(255, 255, 255), scale=2)
lcd.display(img)
try:
task = None
task = kpu.load(model_addr) #加载模型
kpu.init_yolo2(task, 0.5, 0.3, 5, anchors) # threshold:[0,1], nms_value: [0, 1]
while(True):
img = sensor.snapshot()#拍一张照片
t = time.ticks_ms()
objects = kpu.run_yolo2(task, img)#task:SD卡中的模型,img:目前相机拍照的图像,返回一个 kpu_yolo2_find 的列表
t = time.ticks_ms() - t
if objects:
for obj in objects:#取出列表中的对象
pos = obj.rect()#返回一个矩形元组(x, y, w, h) ,用于如色块边界框的 image.draw_rectangle 等
img.draw_rectangle(pos)
img.draw_string(pos[0], pos[1], "%s : %.2f" %(labels[obj.classid()], obj.value()), scale=2, color=(255, 0, 0))
img.draw_string(0, 200, "t:%dms" %(t), scale=2, color=(255, 0, 0))
lcd.display(img)
except Exception as e:
raise e
finally:
if not task is None:
kpu.deinit(task) #释放模型占用的内存, 立即释放, 但是变量还在
if name == "main":
try:
# main(anchors = anchors, labels=labels, model_addr=0x300000, lcd_rotation=0)
main(anchors = anchors, labels=labels, model_addr="/sd/model-9043.kmodel")
except Exception as e:
sys.print_exception(e)
lcd_show_except(e)
finally:
gc.collect()#自动释放内存