我的购物车
资讯分类
全部资讯
最新活动
商城公告
行业信息
新品推荐
元器件知识
资讯标签
iCEasy商城(213) 艾为(AWINIC)(182) 艾迈斯欧司朗(ams OSRAM)(168) NVIDIA(96) 萤火工场(Firefly Workshop)(63) 兆易创新(GigaDevice)(39) 飞腾派V3(33) 赛昉科技(StarFive)(31) 罗彻斯特电子(28) 小华半导体(XHSC)(19) 灵动微电子(MindMotion)(16) 机器人(15) 领麦微(leamems)(14) 芯佰微(14) 日清纺微电子(Nisshinbo Micro devices Inc.)(13) 开源社区活动(13) 矽递科技(Seeed Studio)(11) 雷卯(Leiditech)(8) 微源半导体(LowPowerSemi)(8) 航顺(Hangshun)(8) 极海半导体(Geehy)(8) 物奇(WUQi)(7) 教程(6) 沃虎(WOHU)(6) 高通Qualcomm(5) 峰岹科技(Fortior Tech)(4) 高通(qualcomm)(3) BeagleBoard(3) 英迪芯微(indiemicro)(3) 安世半导体(Nexperia)(3) 博瑞集信(bonray)(3) 艾迈斯欧司朗(2) 开源社区(2) 阿加犀(APLUX)(2) 中科本原(Fdmtek)(2) 芯查查(2) 中电港(1) 硅光电二极管BPW 34 S-Z(1) 英飞凌(Infineon)(1) 蓝光激光二极管PLPT9 450MD_E(1) 森云智能(SENSING)(1) 绿色激光二极管PLT5 520HB_P(1) 移远(Quectel)(1) 红外传感发射器件SFH 4713B(1) 亚德诺半导体(1) 共模半导体(GONGMO)(1) 绘芯微半导体(HXWPRECIC)(1) 领慧立芯(legendsemi)(1) 凌久微(LingJoWing)(1) 飞腾派(1) 艾利光科技(ALG-TECH)(1) 新唐(Nuvoton Technology)(1) 瑞萨电子(RENESAS)(1)

【国产方案】飞腾派数字识别!免费试用申请!

发布时间:2026-01-23

机器视觉整合图像处理与机械控制技术,能提升工业生产灵活性与自动化水平,国产自主可控开源硬件飞腾派凭借强劲算力、良好兼容性与可扩展性,可高效支撑这类视觉应用的开发与部署。

飞腾派识别数字

项目准备

硬件规格:飞腾派

操作系统:飞腾OS(飞腾派OS系统下载:‍https://www.iceasy.com/cloud/Phytium?pid=1877647545995448322)

具体操作:

一、安装Tensorflow lite

安装pip

LeNet = keras.models.Sequential(    [        keras.layers.Conv2D(            input_shape=(32, 32, 1), filters=6, kernel_size=(3, 3), activation="relu"        ),        keras.layers.AveragePooling2D(),        keras.layers.Conv2D(filters=16, kernel_size=(3, 3), activation="relu"),        keras.layers.AveragePooling2D(),        keras.layers.Flatten(),        keras.layers.Dense(units=120, activation="relu"),        keras.layers.Dense(units=84, activation="relu"),        keras.layers.Dense(units=10, activation="softmax"),    ])

安装tflite-runtime

def read_mnist(images_path: str, labels_path: str):    with gzip.open(labels_path, "rb") as labelsFile:        labels = np.frombuffer(labelsFile.read(), dtype=np.uint8, offset=8)    with gzip.open(images_path, "rb") as imagesFile:        length = len(labels)        # Load flat 28x28 px images (784 px), and convert them to 28x28 px        features = (            np.frombuffer(imagesFile.read(), dtype=np.uint8, offset=16)            .reshape(length, 784)            .reshape(length, 28, 28, 1)        )        # LeNet architecture accepts a 32x32 pixel images as input,        # mnist data is 28x28 pixels. We simply pad the images with zeros to overcome        features = np.pad(features, ((0, 0), (2, 2), (2, 2), (0, 0)), "constant")    return features, labelsx_train, y_train = read_mnist(    "train-images-idx3-ubyte.gz", "train-labels-idx1-ubyte.gz")x_test, y_test = read_mnist("t10k-images-idx3-ubyte.gz", "t10k-labels-idx1-ubyte.gz")x_train, x_test = x_train / 255.0, x_test / 255.0

二、训练LeNet模型

LeNet模型由Yann LeCun在1998年设计并提出的,是一种非常经典的卷积神经网络模型,先使用Tensorflow API实现这个模型

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)LeNet.compile(optimizer='adam',              loss=loss_fn,              metrics=['accuracy'])LeNet.fit(x_train, y_train, epochs=5)

载入数据

def read_mnist(images_path: str, labels_path: str):    with gzip.open(labels_path, "rb") as labelsFile:        labels = np.frombuffer(labelsFile.read(), dtype=np.uint8, offset=8)    with gzip.open(images_path, "rb") as imagesFile:        length = len(labels)        # Load flat 28x28 px images (784 px), and convert them to 28x28 px        features = (            np.frombuffer(imagesFile.read(), dtype=np.uint8, offset=16)            .reshape(length, 784)            .reshape(length, 28, 28, 1)        )        # LeNet architecture accepts a 32x32 pixel images as input,        # mnist data is 28x28 pixels. We simply pad the images with zeros to overcome        features = np.pad(features, ((0, 0), (2, 2), (2, 2), (0, 0)), "constant")    return features, labelsx_train, y_train = read_mnist(    "train-images-idx3-ubyte.gz", "train-labels-idx1-ubyte.gz")x_test, y_test = read_mnist("t10k-images-idx3-ubyte.gz", "t10k-labels-idx1-ubyte.gz")x_train, x_test = x_train / 255.0, x_test / 255.0

设置损失函数以及优化器开始训练

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)LeNet.compile(optimizer='adam',              loss=loss_fn,              metrics=['accuracy'])LeNet.fit(x_train, y_train, epochs=5)

评估模型

LeNet.evaluate(x_test,  y_test, verbose=2)
1875/1875 [==============================] - 9s 3ms/step - loss: 0.2255 - accuracy: 0.9328Epoch 2/51875/1875 [==============================] - 6s 3ms/step - loss: 0.0749 - accuracy: 0.9767Epoch 3/51875/1875 [==============================] - 6s 3ms/step - loss: 0.0529 - accuracy: 0.9836Epoch 4/51875/1875 [==============================] - 5s 3ms/step - loss: 0.0408 - accuracy: 0.9869Epoch 5/51875/1875 [==============================] - 5s 3ms/step - loss: 0.0329 - accuracy: 0.9895313/313 - 1s - loss: 0.0341 - accuracy: 0.9897 - 628ms/epoch - 2ms/step

将模型导出为TFLite格式

# convert modelconverter = tf.lite.TFLiteConverter.from_keras_model(LeNet)tflite_model = converter.convert()# Save the model.with open('lenet5.tflite', 'wb') as f:  f.write(tflite_model)
  

在飞腾派部署LeNet模型

首先设置track装饰器,让我们了解飞腾派的推理速度

import timeimport logging as logimport syslog.basicConfig(format='[ %(levelname)s ] %(message)s', level=log.INFO, stream=sys.stdout)def timer(label:str, ms_:bool=True):    def out_wrapper(func):        def wrapper(*args, **kwargs):            st = time.perf_counter()            ret = func(*args, **kwargs)            measure = time.perf_counter() - st            if ms_:                measure *= 1e3            tag = "ms" if ms_ else "s"            log.info(f"{label} elapsed {(measure):.3f} {tag}.")            return ret        return wrapper    return out_wrapper
    

推理函数

@timer("infer")def infer(model:str, input_blob:np.array) -> int:    interpreter = tflite.Interpreter(model_path=model, num_threads=4)    interpreter.allocate_tensors()    input_details = interpreter.get_input_details()    # Get input and output tensors.    output_details = interpreter.get_output_details()    interpreter.set_tensor(input_details[0]['index'], input_blob)    interpreter.invoke()    return np.argmax(interpreter.get_tensor(output_details[0]['index']))
    

运行结果

数字识别全部正确!而且识别速度特别快,轻松满足各类应用需求!

飞腾派免费试用!轻松带走定制文创礼品!

➡️点击查看活动详情

(内附测评分享小tips)