图38.3.2.1 image图像码识别实验流程图
38.3.3 main.py代码
main.py中的脚本代码如下所示:
from board import board_info
from fpioa_manager import fm
from maix import GPIO
import lcd
import sensor
import image
import math
import gc
lcd.init()
sensor.reset()
sensor.set_framesize(sensor.QVGA)
sensor.set_pixformat(sensor.RGB565)
sensor.set_hmirror(False)
type = 0
type_dict = {
0: "Normal",
1: "Barcode",
2: "Data Matrices",
3: "QRCode",
4: "AprilTag"
}
fm.register(board_info.KEY0, fm.fpioa.GPIOHS0)
key0 = GPIO(GPIO.GPIOHS0, GPIO.IN, GPIO.PULL_UP)
def key_irq_handler(key):
global key0
global type
time.sleep_ms(20)
if key is key0 and key.value() == 0:
type = type + 1
if type == len(type_dict):
type = 0
key0.irq(key_irq_handler, GPIO.IRQ_FALLING, GPIO.WAKEUP_NOT_SUPPORT, 7)
while True:
img = sensor.snapshot()
if type == 0:
pass
elif type == 1:
# 条形码识别
roi = (img.width() // 2 - 120, img.height() // 2 - 80, 240, 160)
gray = img.copy(roi).to_grayscale()
img.draw_rectangle(roi, color=(0, 255, 0))
barcodes = gray.find_barcodes((0, 0, gray.width(), gray.height()))
if barcodes:
img.draw_string(10, 30, barcodes[0].payload(), color=(255, 0, 0), scale=1.6)
elif type == 2:
# DM码识别
roi = (img.width() // 2 - 100, img.height() // 2 - 100, 200, 200)
gray = img.copy(roi).to_grayscale()
img.draw_rectangle(roi, color=(0, 255, 0))
datamatrices = gray.find_datamatrices((0, 0, gray.width(), gray.height()))
if datamatrices:
img.draw_string(10, 30, datamatrices[0].payload(), color=(255, 0, 0), scale=1.6)
elif type == 3:
# 二维码识别
roi = (img.width() // 2 - 100, img.height() // 2 - 100, 200, 200)
gray = img.copy(roi).to_grayscale()
img.draw_rectangle(roi, color=(0, 255, 0))
qrcodes = gray.find_qrcodes((0, 0, gray.width(), gray.height()))
if qrcodes:
img.draw_string(10, 30, qrcodes[0].payload(), color=(255, 0, 0), scale=1.6)
elif type == 4:
# AprilTag识别
roi = (img.width() // 2 - 100, img.height() // 2 - 100, 200, 200)
gray = img.copy(roi).to_grayscale()
img.draw_rectangle(roi, color=(0, 255, 0))
apriltags = gray.find_apriltags((0, 0, gray.width(), gray.height()), families=image.TAG36H11)
if apriltags:
def shot_degrees(axis, y, rotation):
degrees = (180 * rotation) / math.pi
img.draw_string(10, y, "{:s}:{:.0f}".format(axis, degrees), color=(255, 0, 0), scale=1.6)
img.draw_string(10, 30, "ID:{:d}".format(apriltags[0].id()), color=(255, 0, 0), scale=1.6)
shot_degrees("X", 50, apriltags[0].x_rotation())
shot_degrees("Y", 70, apriltags[0].y_rotation())
shot_degrees("Z", 90, apriltags[0].z_rotation())
else:
type = 0
img.draw_string(10, 10, type_dict[type], color=(255, 0, 0), scale=1.6)
lcd.display(img)
gc.collect()
可以看到一开始是先初始化了LCD、摄像头和中断按键,并且按下中断按键可以切换不同的码识别方法类识别图像中不同种类的码。
接着在一个循环中不断地获取摄像头输出的图像,因为获取到的图像就是Image对象,因此可以直接调用image模块为Image对象提供的各种方法,然后就是对图像中的码进行检测和识别,并在LCD上绘制识别到码的信息,最后在LCD显示图像。
38.4 运行验证
将DNK210开发板连接CanMV IDE,点击CanMV IDE上的“开始(运行脚本)”按钮后,便能看到LCD上显示了摄像头输出的图像,并能看一个绿色的识别框,但将对应的码移入识别框后,能够看到LCD的左上角显示了识别到的结果,按下KEY0按键还能够切换识别码的种类,以识别不同种类的码,如下图所示: