Note

This is the documentation for the latest development branch and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version.

QR Code Recognition Example Explanation

Contents

QR Code Recognition Example Explanation#

Overview#

CanMV supports the OpenMV algorithm and can recognize QR codes. The relevant interface is find_qrcodes.

Example#

This example configures the camera to output a 640x480 grayscale image and uses image.find_qrcodes to recognize QR codes.

Tip

If the recognition success rate is low, try adjusting the camera’s mirror and flip settings.

# QR 码示例
import time
import os
import gc
import sys

from media.sensor import *
from media.display import *
from media.media import *

DETECT_WIDTH = 640
DETECT_HEIGHT = 480

sensor = None

try:
    # 使用默认配置构造 Sensor 对象
    sensor = Sensor(width=DETECT_WIDTH, height=DETECT_HEIGHT)
    # 重置 sensor
    sensor.reset()
    # 设置水平镜像
    # sensor.set_hmirror(False)
    # 设置垂直翻转
    # sensor.set_vflip(False)
    # 设置输出大小
    sensor.set_framesize(width=DETECT_WIDTH, height=DETECT_HEIGHT)
    # 设置输出格式
    sensor.set_pixformat(Sensor.GRAYSCALE)

    # 初始化显示,如果选择的屏幕无法点亮,请参考 API 文档中的 K230_CanMV_Display 模块 API 手册进行配置
    # 使用 HDMI 输出,设置为 VGA
    # Display.init(Display.LT9611, width=640, height=480, to_ide=True)

    # 使用 HDMI 输出,设置为 1080P
    # Display.init(Display.LT9611, width=1920, height=1080, to_ide=True)

    # 使用 LCD 输出
    # Display.init(Display.ST7701, to_ide=True)

    # 使用 IDE 输出
    Display.init(Display.VIRT, width=DETECT_WIDTH, height=DETECT_HEIGHT, fps=100)

    # 初始化媒体管理器
    MediaManager.init()
    # 启动 sensor
    sensor.run()

    fps = time.clock()

    while True:
        fps.tick()

        # 检查是否应该退出
        os.exitpoint()
        img = sensor.snapshot()

        for code in img.find_qrcodes():
            rect = code.rect()
            img.draw_rectangle([v for v in rect], color=(255, 0, 0), thickness=5)
            img.draw_string_advanced(rect[0], rect[1], 32, code.payload())
            print(code)

        # 将结果绘制到屏幕上
        Display.show_image(img)
        gc.collect()

        # print(fps.fps())
except KeyboardInterrupt as e:
    print(f"user stop")
except BaseException as e:
    print(f"Exception '{e}'")
finally:
    # 停止 sensor
    if isinstance(sensor, Sensor):
        sensor.stop()
    # 取消初始化显示
    Display.deinit()

    os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
    time.sleep_ms(100)

    # 释放媒体缓冲区
    MediaManager.deinit()

Tip

For specific interface definitions, please refer to find_qrcodes.

Comments list
Comments
Log in