本文最后更新于335 天前,其中的信息可能已经过时,如有错误请发送邮件到273925452@qq.com
一、入门教程

这是大二学习的K210模块的学习笔记,现在把它整理出来😀
模块 说明
CPU: 双核 64bit RISC-V / 400MHz (双精度FPU集成)
内存: 8MiB 64bit 片上 SRAM
存储: 16MiB Flash, 支持 micro SDXC 拓展存储 (最大128GB)
屏幕(套餐): 2.4 寸 TFT, 屏幕分辨率:320*240
摄像头(套餐): 200W 像素(实际使用 30W),0V2640 型号 M12 摄像头
TF 卡槽: 多媒体资源扩展,支持大容量储存
原理图
IO资源
第一列为板载IO口,Maix Bit 引出来了36个引脚,另外的12各引脚分配给了LCD、摄像头。
第三行是缺省功能,为原始固件上电默认功能。在此也可以看出,0-3号引脚上是JTAG;4、5号引脚为默认串口;12-14号是RGB灯;16号引脚是BOOT键,接了10kΩ的上拉电阻;18-20号引脚接的是麦克风;26-28号引脚是用SPI协议实现的的读写TF card功能。
第五行为IO电压,IO引脚都是3.3V,Reset引脚电压为1.8V。
历程
般历程
寻找色块
识别最大色块并且串口或者屏幕输出最大色块中心坐标
import sensor,lcd,time,image
from machine import UART,Timer
from fpioa_manager import fm
#fm.register(15, fm.fpioa.UART1_RX, force=True)
#fm.register(17, fm.fpioa.UART1_TX, force=True)
#uart = UART(UART.UART1, 115200, read_buf_len=4096)
#uart.write('Hello world!')
clock = time.clock()
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA) #QVGA(320X240)
sensor.set_vflip(1) #后置模式,所见即所得
sensor.skip_frames(time = 1000) # 等待设置生效.
#sensor.snapshot(1.8)#去鱼眼化
arr=[1,2,4,0]#存放颜色的代号
#**** clock=time.clock()
#**** 颜色识别阈值 (L Min, L Max, A Min, A Max, B Min, B Max) LAB 模型
#**** 下面的阈值元组是用来识别 红、绿、蓝三种颜色,当然你也可以调整让识别变得更好。
thresholds = [(16, 97, 10, 50, -19, 47), # 红色阈值
(13, 95, 37, -100, 105, 27), # 绿色阈值
(78, 21, -112, 75, -64, -18), # 蓝色阈值
(100, 40, -107, 14, 22, 76)] # 黄色阈值
#寻找最大色块算法
def find_max(blobs):
max_size=0
for blob in blobs:
if blob.pixels() > max_size:
max_blob=blob
max_size = blob.pixels()
return max_blob
while True:
clock.tick()
img = sensor.snapshot()
#**以下注释打开roi区域,0,1,2,4 分别表示红,绿,蓝色。
#**blobs = img.find_blobs(thresholds,roi=(130,80,70,70),pixels_threshold = 250,area_threshold = 250,margin=5,merge = False)
blobs = img.find_blobs(thresholds,pixels_threshold = 250,area_threshold = 250,margin=5,merge = False) # 0,2,4 8分别表示红,绿,蓝色,黄。
#**获取图像帧率
fps =clock.fps()
if blobs: #->如果找到了目标颜色
max_blob=find_max(blobs) #->调用寻找最大色块函数
for b in blobs: #循环效果不好,会有很多误识别,采用单个矩形采样方便返回坐标
tmp=img.draw_cross(b[5], b[6])#在中心画十字
img.draw_rectangle((max_blob.x(),max_blob.y(),max_blob.w(),max_blob.h()),color=(255,0,0))#用红色框出最大色块
img.draw_string(max_blob.x(),max_blob.y(), "(x,y) =")
img.draw_string(max_blob.x()+40,max_blob.y(), str(max_blob.cx()))
img.draw_string(max_blob.x()+60,max_blob.y(), str(max_blob.cy()))#在框图左上角显示色块的中心坐标
#output_str="[%d,%d]" % (max_blob.cx(),max_blob.cy()) #方式1
#output_str=json.dumps([max_blob.cx(),max_blob.cy()]) #方式2
#uart.write(output_str+'\r\n')
# text=uart.read() #读取数据
# if text: #如果读取到了数据
# print(text.decode('utf-8')) #REPL 打印
# uart.write('I got'+text.decode('utf-8')) #数据回传
#串口终端输出
a=b[8] #[8]索引得到code的代码
if a==1:
img.draw_string(max_blob.x(),max_blob.y()+20, "1")
#print('红色')
elif a==2:
img.draw_string(max_blob.x(),max_blob.y()+20, "2")
#print('绿色')
elif a==4:
img.draw_string(max_blob.x(),max_blob.y()+20, "4")
#print('蓝色')
else :
img.draw_string(max_blob.x(),max_blob.y()+20, "8")
#print('黄色')
#开启屏幕显示
img.draw_string(2,2, ("%2.1ffps" %(fps)), color=(0,128,0), scale=2)
lcd.display(img) #LCD 显示图片
import sensor,image,lcd,time
#常用初始化
lcd.init()
sensor.reset() #复位摄像头
sensor.set_pixformat(sensor.RGB565) #设置像素格式 RGB565
sensor.set_framesize(sensor.QVGA) #设置帧尺寸 QVGA (320x240)
sensor.skip_frames(time = 2000) #跳过不稳定画面
#红色阈值
red_threshold = (87, 21, 27, 93, -5, 92)
#蓝色阈值
blue_threshold = (14, 87, -83, 127, -113, -14)
#寻找最大色块函数定义
def find_max(blobs):
max_size=0
for blob in blobs:
if blob[2]*blob[3] > max_size:
max_blob=blob
max_size = blob[2]*blob[3]
return max_blob
while True:
img=sensor.snapshot()
blobs = img.find_blobs([blue_threshold],merge=True)#把拍摄的一张图片里满足的色块纳入集合中
if blobs:
max_blob = find_max(blobs)#调用函数,返回最大色块
img.draw_rectangle((max_blob.x(),max_blob.y(),max_blob.w(),max_blob.h()),color=(255,0,0))#用红色框出最大色块
img.draw_string(max_blob.x(),max_blob.y(), "(x,y) =")
img.draw_string(max_blob.x()+40,max_blob.y(), str(max_blob.cx()))
img.draw_string(max_blob.x()+60,max_blob.y(), str(max_blob.cy()))#在框图左上角显示色块的中心坐标
lcd.display(img)
寻找所有色块并标注坐标
import sensor,lcd,time,image
from machine import UART,Timer
from fpioa_manager import fm
fm.register(15, fm.fpioa.UART1_RX, force=True)
fm.register(17, fm.fpioa.UART1_TX, force=True)
uart = UART(UART.UART1, 115200, read_buf_len=4096)
#uart.write('Hello world!')
clock = time.clock()
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA) #QVGA(320X240)
sensor.set_vflip(1) #后置模式,所见即所得
sensor.skip_frames(time = 1000) # 等待设置生效.
#sensor.snapshot(1.8)#去鱼眼化
arr=[1,2,4,0]#存放颜色的代号
#clock=time.clock()
# 颜色识别阈值 (L Min, L Max, A Min, A Max, B Min, B Max) LAB 模型
# 下面的阈值元组是用来识别 红、绿、蓝三种颜色,当然你也可以调整让识别变得更好。
thresholds = [(16, 97, 10, 50, -19, 47), # 红色阈值
(13, 95, 37, -100, 105, 27), # 绿色阈值
(78, 21, -112, 75, -64, -18),# 蓝色阈值
(100, 40, -107, 14, 22, 76)] # 黄色阈值
def find_max(blobs):
max_size=0
for blob in blobs:
if blob.pixels() > max_size:
max_blob=blob
max_size = blob.pixels()
return max_blob
while True:
clock.tick()
img = sensor.snapshot()
#blobs = img.find_blobs(thresholds,roi=(130,80,70,70),pixels_threshold = 250,area_threshold = 250,margin=5,merge = False) # 0,1,2 分别表示红,绿,蓝色。
blobs = img.find_blobs(thresholds,pixels_threshold = 250,area_threshold = 250,margin=5,merge = False) # 0,1,2 分别表示红,绿,蓝色。
fps =clock.fps()
if blobs:#如果找到了目标颜色
for b in blobs:#循环效果不好,会有很多误识别,采用单个矩形采样方便返回坐标
#tmp=img.draw_rectangle(b[0:4])#画矩形
#tmp=img.draw_cross(b[5], b[6])#在中心画十字
x=b[0]
y=b[1]
width=b[2]
height=b[3]
img.draw_rectangle((x,y,width,height),color=(255,0,0))#用红色框出所有
img.draw_string(x,y, "(x,y) =")
img.draw_string(x+40,y, str(x))
img.draw_string(x+60,y, str(y))#在框图左上角显示色块的中心坐标
a=b[8] #[8]索引得到code的代码
if a==1:
print('红色')
elif a==2:
print('绿色')
elif a==4:
print('蓝色')
else :
print('黄色')
output_str="[%d,%d]" % (max_blob.cx(),max_blob.cy()) #方式1
#output_str=json.dumps([max_blob.cx(),max_blob.cy()]) #方式2
uart.write(output_str+'\r\n')
# text=uart.read() #读取数据
# if text: #如果读取到了数据
# print(text.decode('utf-8')) #REPL 打印
# uart.write('I got'+text.decode('utf-8')) #数据回传
img.draw_string(2,2, ("%2.1ffps" %(fps)), color=(0,128,0), scale=2)
lcd.display(img) #LCD 显示图片
寻找最大色块并标注面积,像素,像素占比
import sensor,lcd,time,image
from machine import UART,Timer
from fpioa_manager import fm
fm.register(15, fm.fpioa.UART1_RX, force=True)
fm.register(17, fm.fpioa.UART1_TX, force=True)
uart = UART(UART.UART1, 115200, read_buf_len=4096)
#uart.write('Hello world!')
clock = time.clock()
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA) #QVGA(320X240)
sensor.set_vflip(1) #后置模式,所见即所得
sensor.skip_frames(time = 1000) # 等待设置生效.
#sensor.snapshot(1.8)#去鱼眼化
arr=[1,2,4,0] #存放颜色的代号
K=5000 # K=length*Lm 实际的大小=K2*直径的像素
K2=10.5/279 # QQVGA模式下K2=10.5/139 #QVGA模式下K2=10.5/279
#clock=time.clock()
# 颜色识别阈值 (L Min, L Max, A Min, A Max, B Min, B Max) LAB 模型
# 下面的阈值元组是用来识别 红、绿、蓝三种颜色,当然你也可以调整让识别变得更好。
thresholds = [(16, 97, 10, 50, -19, 47), # 红色阈值
(13, 95, 37, -100, 105, 27), # 绿色阈值
(78, 21, -112, 75, -64, -18),# 蓝色阈值
(100, 40, -107, 14, 22, 76)] # 黄色阈值
#********寻找最大色块******************
def find_max(blobs):
max_size=0
for blob in blobs:
if blob.pixels() > max_size:
max_blob=blob
max_size = blob.pixels()
return max_blob
#**************************************
while True:
clock.tick()
img = sensor.snapshot()
#****以下注释是打开选定目标区域来识别************
#blobs = img.find_blobs(thresholds,roi=(130,80,70,70),pixels_threshold = 250,area_threshold = 250,margin=5,merge = False) # 0,1,2 分别表示红,绿,蓝色。
#**识别色块
blobs = img.find_blobs(thresholds,pixels_threshold = 250,area_threshold = 250,margin=5,merge = False) # 0,1,2 分别表示红,绿,蓝色。
fps =clock.fps()
if blobs: #如果找到了目标颜色
max_blob=find_max(blobs) #寻找最大色块
for b in blobs: #循环效果不好,会有很多误识别,采用单个矩形采样方便返回坐标
x=max_blob.x() #最大色块x坐标
y=max_blob.y() #最大色块y坐标
width=max_blob.w() #最大色块宽度
height=max_blob.h() #最大色块高度
img.draw_rectangle((x,y,width,height),color=(255,0,0)) #用红色框出最大色块
Lm=(width+height)/2 #色块的外框的宽,外框高,得到像素点
pixels=max_blob.pixels() #色块的像素数量
length=K/Lm #长度
size=K2*Lm #色块的外框的平均直径
K3=13/140
b2=K3*width
b3=K3*height
K4=17.74*12.9/24846
area=pixels*K4 #物体的面积
ratio=pixels/76241*100 #76241为摄像头检测出来的像素点个数
#*************图像数据显示******************
img.draw_string(x,y,"area=")
img.draw_string(x+40,y,str(area)) #面积
img.draw_string(x,y+10, "pixels=") #像素点
img.draw_string(x+40, y+10, str(pixels)) #写像素点。
img.draw_string(x,y+20, "pixel ratio=") #像素占比
img.draw_string(x+60, y+20, str(ratio)) #像素占比
a=b[8] #[8]索引得到code的代码
if a==1:
img.draw_string(max_blob.x(),max_blob.y()+20, "1")
# print('红色')
elif a==2:
img.draw_string(max_blob.x(),max_blob.y()+20, "2")
# print('绿色')
elif a==4:
img.draw_string(max_blob.x(),max_blob.y()+20, "4")
#print('蓝色')
else :
img.draw_string(max_blob.x(),max_blob.y()+20, "8")
#print('黄色')
#output_str="[%d,%d]" % (max_blob.cx(),max_blob.cy()) #方式1
#output_str=json.dumps([max_blob.cx(),max_blob.cy()]) #方式2
#uart.write(output_str+'\r\n')
# text=uart.read() #读取数据
# if text: #如果读取到了数据
# print(text.decode('utf-8')) #REPL 打印
# uart.write('I got'+text.decode('utf-8')) #数据回传
img.draw_string(2,2, ("%2.1ffps" %(fps)), color=(0,128,0), scale=2)
lcd.display(img) #LCD 显示图片
寻找所有色块并标注面积,像素,像素占比
import sensor,lcd,time,image
from machine import UART,Timer
from fpioa_manager import fm
fm.register(15, fm.fpioa.UART1_RX, force=True)
fm.register(17, fm.fpioa.UART1_TX, force=True)
uart = UART(UART.UART1, 115200, read_buf_len=4096)
#uart.write('Hello world!')
clock = time.clock()
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA) #QVGA(320X240)
sensor.set_vflip(1) #后置模式,所见即所得
sensor.skip_frames(time = 1000) # 等待设置生效.
#sensor.snapshot(1.8)#去鱼眼化
arr=[1,2,4,0]#存放颜色的代号
K=5000 # K=length*Lm 实际的大小=K2*直径的像素
K2=10.5/101 #QQVGA模式下K2=10.5/139 #QVGA模式下K2=10.5/279
#clock=time.clock()
# 颜色识别阈值 (L Min, L Max, A Min, A Max, B Min, B Max) LAB 模型
# 下面的阈值元组是用来识别 红、绿、蓝三种颜色,当然你也可以调整让识别变得更好。
thresholds = [(16, 97, 10, 50, -19, 47), # 红色阈值
(13, 95, 37, -100, 105, 27), # 绿色阈值
(78, 21, -112, 75, -64, -18),# 蓝色阈值
(100, 40, -107, 14, 22, 76)] # 黄色阈值
def find_max(blobs):
max_size=0
for blob in blobs:
if blob.pixels() > max_size:
max_blob=blob
max_size = blob.pixels()
return max_blob
while True:
clock.tick()
img = sensor.snapshot()
#blobs = img.find_blobs(thresholds,roi=(130,80,70,70),pixels_threshold = 250,area_threshold = 250,margin=5,merge = False) # 0,1,2 分别表示红,绿,蓝色。
blobs = img.find_blobs(thresholds,pixels_threshold = 250,area_threshold = 250,margin=5,merge = False) # 0,1,2 分别表示红,绿,蓝色。
fps =clock.fps()
if blobs:#如果找到了目标颜色
#max_blob=find_max(blobs)#寻找最大色块
for b in blobs:#循环效果不好,会有很多误识别,采用单个矩形采样方便返回坐标
x=b[0]
y=b[1]
width=b[2]
height=b[3]
img.draw_rectangle((x,y,width,height),color=(255,0,0))#用红色框出所有
Lm=(b[2]+b[3])/2#b[2]色块的外框的宽,b[3]外框高,得到像素点
pixels=b[4]#色块的像素数量
length=K/Lm #长度
size=K2*Lm #色块的外框的平均直径
K3=13/140
b2=K3*b[2]
b3=K3*b[3]
K4=17.74*12.9/24846
area=pixels*K4 #物体的面积
ratio=pixels/76241*100 #76241为摄像头检测出来的像素点个数
img.draw_string(x,y,"area=")
img.draw_string(x+40,y,str(area))
img.draw_string(x,y+10, "pixels=")#像素点
img.draw_string(x+40, y+10, str(pixels))#写像素点。
img.draw_string(x,y+20, "pixel ratio=")#像素占比
img.draw_string(x+60, y+20, str(ratio))#像素占比
a=b[8] #[8]索引得到code的代码
if a==1:
print('红色')
elif a==2:
print('绿色')
elif a==4:
print('蓝色')
else :
print('黄色')
#output_str="[%d,%d]" % (max_blob.cx(),max_blob.cy()) #方式1
#output_str=json.dumps([max_blob.cx(),max_blob.cy()]) #方式2
#uart.write(output_str+'\r\n')
# text=uart.read() #读取数据
# if text: #如果读取到了数据
# print(text.decode('utf-8')) #REPL 打印
# uart.write('I got'+text.decode('utf-8')) #数据回传
img.draw_string(2,2, ("%2.1ffps" %(fps)), color=(0,128,0), scale=2)
lcd.display(img) #LCD 显示图片
串口通信
import sensor, image, lcd, time
import KPU as kpu
import gc, sys
import ustruct
from fpioa_manager import fm
from machine import UART
# need your connect hardware IO 10/11 to loopback
fm.register(5, fm.fpioa.UART1_TX, force=True)
fm.register(4, fm.fpioa.UART1_RX, force=True)
uart = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096)
#你想发的数据
uart.write('4')
fm.register(15, fm.fpioa.UART1_RX, force=True)
fm.register(17, fm.fpioa.UART1_TX, force=True)
uart = UART(UART.UART1, 115200, read_buf_len=4096)
uart.write('Hello world!')
output_str="[%d,%d]" % (max_blob.cx(),max_blob.cy()) #方式1
#output_str=json.dumps([max_blob.cx(),max_blob.cy()]) #方式2
uart.write(output_str+'\r\n')
# text=uart.read() #读取数据
# if text: #如果读取到了数据
# print(text.decode('utf-8')) #REPL 打印
# uart.write('I got'+text.decode('utf-8')) #数据回传
数据打包
def sending_data(cx,cy,ch):
global uart;
#frame=[0x2C,18,cx%0xff,int(cx/0xff),cy%0xff,int(cy/0xff),0x5B];
#data = bytearray(frame)
data = ustruct.pack("<bbhhhb", #格式为俩个字符俩个短整型(2字节)
0x2C, #帧头1
0x12, #帧头2
int(cx), # up sample by 4 #数据1
int(cy), # up sample by 4 #数据2
int(ch),
0x5B)
uart = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096)
uart.write(data); #必须要传入一个字节数组
呼吸灯
from machine import Timer,PWM
from board import board_info
import time
tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
ch = PWM(tim, freq=500000, duty=50, pin=board_info.LED_G)
duty=0
dir = True
while True:
if dir:
duty += 10
else:
duty -= 10
if duty>100:
duty = 100
dir = False
elif duty<0:
duty = 0
dir = True
time.sleep(0.05)
ch.duty(duty)
图片采集脚本
需要去官网下载脚本
使用方法
- 根据你的开发板修改摄像头和屏幕配置, 比如lcd.rotation
- 准备一张支持 SPI 模式的 SD 卡, 分区为 MBR (msdos), 格式化为 FAT32
- 将目录下的boot.py文件拷贝到 SD 卡根目录
- 开发板断电, 将SD卡插入开发板
- 开发板上电, 程序会自动创建一个目录cap_images_1, 下次上电会创建cap_images_2, 这样就避免了覆盖
- 采集一个分类的图片按开发板上的boot按键,然后松开按键来采集一张图片,这会将图片保存到
cap_images_1/0/0.jpg,采集的图片的名字会自动增长, 比如0.jpg 1.jpg …
- 长按boot按键切换类别目录这会创建一个新目录,比如cap_images_1/1/,后面采集的图片都会被保存到这个新的目录, 比如cap_images_1/1/0.jpg
- 开发板断电,取出SD卡插到电脑, 打开文件管理器就可以看到采集的图片了
训练网站 MaixHub
'''
image caupture tool, capture images to SD card with directory switch support
@usage 1. Change camera and lcd configs according to your hardware like `lcd.rotation`
2. Prepare a SD card with SPI mode support, and format to FAT32 with MBR(msdos) partition
3. Copy this boot.py to your SD card root directory
4. Power off board, then insert SD card to board
5. Power on, it will automatically create a directory like `cap_images_1`,
the next time will be `cap_images_2` to avoid rewrite
6. Capture images for one class,
push `boot` button on board and release to capture one image,
this will save images as `cap_images_1/0/0.jpg`,
the name of image will automaitcally increase, like `0.jpg` `1.jpg` ...
7. Long push `boot` botton on board to switch class,
this will create a new directory like `cap_images_1/1/`,
and later captured images will be saved to this directory like `cap_images_1/1/0.jpg`
8. Power off board, pop out SD card, mount on your PC, now you get your images in your file brower
@update https://github.com/sipeed/MaixPy_scripts
@author neucrack@sipeed
@license MIT
'''
import sensor, lcd
from Maix import GPIO
from fpioa_manager import fm
from board import board_info
import os, sys
import time
import image
#### image size ####
set_windowing = (224, 224)
#### sensor config ####
sensor.reset(freq=22000000, dual_buff=False)
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA) # 320x240
try:
sensor.set_jb_quality(95) # for IDE display quality
except Exception:
pass # no IDE support
if set_windowing:
sensor.set_windowing(set_windowing)
# sensor.set_auto_gain(False)
# sensor.set_auto_whitebal(False, rgb_gain_db=(0x52,0x40,0x4d))
# sensor.set_saturation(0)
# sensor.set_brightness(4)
# sensor.set_contrast(0)
# sensor.set_hmirror(True) # image horizonal mirror
# sensor.set_vflip(True) # image vertical flip
# sensor.set_auto_whitebal(False)
sensor.skip_frames()
#### lcd config ####
lcd.init(type=1, freq=15000000)
lcd.rotation(2)
sensor.set_hmirror(0) #水平镜像 enable: 1 表示开启水平镜像 0 表示关闭水平镜像
#### boot key ####
boot_pin = 16 # board_info.BOOT_KEY
fm.register(boot_pin, fm.fpioa.GPIOHS0)
key = GPIO(GPIO.GPIOHS0, GPIO.PULL_UP)
######################################################
#### main ####
def capture_main(key):
def draw_string(img, x, y, text, color, scale, bg=None , full_w = False):
if bg:
if full_w:
full_w = img.width()
else:
full_w = len(text)*8*scale+4
img.draw_rectangle(x-2,y-2, full_w, 16*scale, fill=True, color=bg)
img = img.draw_string(x, y, text, color=color,scale=scale)
return img
def del_all_images():
os.chdir("/sd")
images_dir = "cap_images"
if images_dir in os.listdir():
os.chdir(images_dir)
types = os.listdir()
for t in types:
os.chdir(t)
files = os.listdir()
for f in files:
os.remove(f)
os.chdir("..")
os.rmdir(t)
os.chdir("..")
os.rmdir(images_dir)
# del_all_images()
os.chdir("/sd")
dirs = os.listdir()
images_dir = "cap_images"
last_dir = 0
for d in dirs:
if d.startswith(images_dir):
if len(d) > 11:
n = int(d[11:])
if n > last_dir:
last_dir = n
images_dir = "{}_{}".format(images_dir, last_dir+1)
print("save to ", images_dir)
if images_dir in os.listdir():
img = image.Image()
img = draw_string(img, 2, 200, "please del cap_images dir", color=lcd.WHITE,scale=1, bg=lcd.RED)
lcd.display(img)
sys.exit(1)
os.mkdir(images_dir)
last_cap_time = 0
last_btn_status = 1
save_dir = 0
save_count = 0
os.mkdir("{}/{}".format(images_dir, save_dir))
while(True):
img0 = sensor.snapshot()
if set_windowing:
img = image.Image()
img = img.draw_image(img0, (img.width() - set_windowing[0])//2, img.height() - set_windowing[1])
else:
img = img0.copy()
# img = img.resize(320, 240)
if key.value() == 0:
time.sleep_ms(30)
if key.value() == 0 and (last_btn_status == 1) and (time.ticks_ms() - last_cap_time > 500):
last_btn_status = 0
last_cap_time = time.ticks_ms()
else:
if time.ticks_ms() - last_cap_time > 5000:
img = draw_string(img, 2, 200, "release to change type", color=lcd.WHITE,scale=1, bg=lcd.RED)
else:
img = draw_string(img, 2, 200, "release to capture", color=lcd.WHITE,scale=1, bg=lcd.RED)
if time.ticks_ms() - last_cap_time > 2000:
img = draw_string(img, 2, 160, "keep push to change type", color=lcd.WHITE,scale=1, bg=lcd.RED)
else:
time.sleep_ms(30)
if key.value() == 1 and (last_btn_status == 0):
if time.ticks_ms() - last_cap_time > 5000:
img = draw_string(img, 2, 200, "change object type", color=lcd.WHITE,scale=1, bg=lcd.RED)
lcd.display(img)
time.sleep_ms(1000)
save_dir += 1
save_count = 0
dir_name = "{}/{}".format(images_dir, save_dir)
os.mkdir(dir_name)
else:
draw_string(img, 2, 200, "capture image {}".format(save_count), color=lcd.WHITE,scale=1, bg=lcd.RED)
lcd.display(img)
f_name = "{}/{}/{}.jpg".format(images_dir, save_dir, save_count)
img0.save(f_name, quality=95)
save_count += 1
last_btn_status = 1
img = draw_string(img, 2, 0, "will save to {}/{}/{}.jpg".format(images_dir, save_dir, save_count), color=lcd.WHITE,scale=1, bg=lcd.RED, full_w=True)
lcd.display(img)
del img
del img0
def main():
try:
capture_main(key)
except Exception as e:
print("error:", e)
import uio
s = uio.StringIO()
sys.print_exception(e, s)
s = s.getvalue()
img = image.Image()
img.draw_string(0, 0, s)
lcd.display(img)
main()
LCD
模板
import sensor, lcd
import image #显示图片
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.run(1)
sensor.skip_frames()
lcd.init()
lcd.mirror(False)#镜像
lcd.rotation(2)#镜头方向0.1.2.3顺时针
while(True):
lcd.display(sensor.snapshot())#显示镜头捕捉画面
镜像
lcd.mirror(True)#镜像
sensor.set_hmirror(enable) #水平镜像 enable: 1 表示开启水平镜像 0 表示关闭水平镜像
sensor.set_vflip(enable)#设置摄像头垂直翻转 enable: 1 表示开启垂直翻转 0 表示关闭垂直翻转
镜头方向
lcd.rotation(2)#镜头方向0.1.2.3顺时针
显示镜头
lcd.display(sensor.snapshot())#显示镜头捕捉画面
显示字符
import lcd
lcd.init()
lcd.draw_string(100, 100, "hello maixpy", lcd.RED, lcd.BLACK)
import lcd
import image
img = image.Image()
img.draw_string(60, 100, "hello maixpy", scale=2)
lcd.display(img)
显示图片
import lcd
import image
img = image.Image("/sd/pic.bmp")
lcd.display(img)
6.image
1.找绿色
import sensor
import image
import lcd
import time
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.run(1)
green_threshold = (0, 80, -70, -10, -0, 30)
while True:
img=sensor.snapshot()
blobs = img.find_blobs([green_threshold])
if blobs:
for b in blobs:
tmp=img.draw_rectangle(b[0:4])
tmp=img.draw_cross(b[5], b[6])
c=img.get_pixel(b[5], b[6])
lcd.display(img)
2.显示 fps
import sensor
import image
import lcd
import time
clock = time.clock()
lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.run(1)
sensor.skip_frames(30)
while True:
clock.tick()
img = sensor.snapshot()
fps =clock.fps()
img.draw_string(2,2, ("%2.1ffps" %(fps)), color=(0,128,0), scale=2)
lcd.display(img)
神经网络模型
人脸检测
05436f871be460eb189b74e465ab4eee
这里需要一个人脸检测的模型下载
模型(使用kflash_gui下载)
#引入kpu模块
import sensor,lcd,time
import KPU as kpu
#设置摄像头
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
#sensor.set_vflip(1) #设置摄像头后置
lcd.init() #LCD初始化
clock = time.clock()
task = kpu.load(0x300000) #需要将模型(face.kfpkg)烧写到flash的 0x300000 位置
#task = kpu.load("/sd/facedetect.kmodel") #模型SD卡上
#模型描参数
anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)
#初始化yolo2网络
a = kpu.init_yolo2(task, 0.5, 0.3, 5, anchor)
while(True):
clock.tick()
img = sensor.snapshot()
code = kpu.run_yolo2(task, img) #运行yolo2网络
#识别到人脸就画矩形表示
if code:
for i in code:
print(i)
b = img.draw_rectangle(i.rect())
#LCD显示
lcd.display(img)
print(clock.fps()) #打印FPS
2、1-8数字卡片识别 并通过串口发送打包数据
模型工程链接:
代码
# object detector boot.py
# generated by maixhub.com
import sensor, image, lcd, time
import KPU as kpu
import gc, sys
import ustruct
from fpioa_manager import fm
from machine import UART
fm.register(5, fm.fpioa.UART1_TX, force=True)
fm.register(4, fm.fpioa.UART1_RX, force=True)
uart = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096)
arr=[1,2,3,4,5,6,7,8]#存放指令
#**************************传输数据的函数********************************************************
'''
ustruct
打包和解压缩原始数据类型
支持的大小/字节顺序前缀: @, <, >, !.
支持的格式编码: b, B, h, H, i, I, l,L, q, Q, s, P, f, d 后两个取决于浮点支持)。
'''
def sending_data(code):
global uart;
#frame=[0x2C,18,cx%0xff,int(cx/0xff),cy%0xff,int(cy/0xff),0x5B];
#data = bytearray(frame)
data = ustruct.pack("<bbhb", #格式为4个字符1个短整型(2字节)
0x2C, #帧头1
0x12, #帧头2
int(code), # up sample by 4 #数据1 分为低八位和高八位,先发低后发高
#int(cy), # up sample by 4 #数据2
0x5B)
uart.write(data); #必须要传入一字节的数组,这个函数似乎不能发送单个字节,必须得一次发送多个字节
#**********************************************************************************************
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=(224,224))
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=(224, 224), lcd_rotation=0, sensor_hmirror=False, sensor_vflip=False):
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_windowing(sensor_window)
sensor.set_hmirror(sensor_hmirror)
sensor.set_vflip(sensor_vflip)
sensor.run(1)
lcd.init(type=1)
lcd.rotation(lcd_rotation)
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: #如果try 执行错误就执行这里
img = image.Image(size=(320, 240))
img.draw_string(90, 110, "loading model...", color=(255, 255, 255), scale=2)
lcd.display(img)
#执行任务模型
task = kpu.load(model_addr)
kpu.init_yolo2(task, 0.5, 0.3, 5, anchors) # threshold:[0,1], nms_value: [0, 1]
try:
while 1:
img = sensor.snapshot()#捕捉图像
t = time.ticks_ms() #创建ms对象
objects = kpu.run_yolo2(task, img) #创建模型对象
t = time.ticks_ms() - t
if objects: #检测到对象,执行循环
for obj in objects:
pos = obj.rect() #创建坐标对象
img.draw_rectangle(pos)
img.draw_string(pos[0], pos[1], "%s : %.2f" %(labels[obj.classid()], obj.value()), scale=2, color=(255, 0, 0))#画出数字标签
#labels[obj.classid()] 为标签号,obj.value()为相似度
img.draw_string(pos[0], pos[1], "[%s,%d]"%(pos[0],pos[1]), scale=2, color=(255, 0, 0))#画出坐标
x=labels[obj.classid()]
#print(x)
if x=='1':
sending_data(str(arr[0]))
elif x=='2':
sending_data(str(arr[1]))
elif x=='3':
sending_data(str(arr[2]))
elif x=='4':
sending_data(str(arr[3]))
elif x=='5':
sending_data(str(arr[4]))
elif x=='6':
sending_data(str(arr[5]))
elif x=='7':
sending_data(str(arr[6]))
elif x=='8':
sending_data(str(arr[7]))
else : uart.write('error')
img.draw_string(0, 200, "t:%dms" %(t), scale=2, color=(255, 0, 0))
lcd.display(img)
#关闭摄像头后要显示的内容
except Exception as e:
raise e
finally:
kpu.deinit(task)
if __name__ == "__main__":
try:
labels = ['1', '2', '3', '4', '5', '6', '7', '8']
anchors = [1.40625, 1.8125000000000002, 5.09375, 5.28125, 3.46875, 3.8124999999999996, 2.0, 2.3125, 2.71875, 2.90625]
#main(anchors = anchors, labels=labels, model_addr=0x300000, lcd_rotation=2, sensor_window=(224, 224))
main(anchors = anchors, labels=labels, model_addr="/sd/m.kmodel", lcd_rotation=2, sensor_window=(224, 224))
except Exception as e:
sys.print_exception(e)
lcd_show_except(e)
finally:
gc.collect()
评论