本来计划使用 art-pi smart 进行车标识别的,但是现在实际测试发现摄像头采集的数据显示有大概率抖动的现象发生,所以实现了将摄像头采集的数据以 bmp 图片格式存储,然后发送到电脑端使用 tflite 格式的模型数据进行测试。
第一部分,系统概述
该项目实现了在 art-pi smart 上通过 ov5640 摄像头采集视频数据,并以 bmp 格式图片保存在设备端,然后借助 art-pi smart webserver 服务将生成的 bmp 图片下载到 pc,然后在 pc 端使用训练的 tflite 模型对下载的 bmp 图片进行预测输出结果。
硬件框图:
软件框图:
第二部分,系统流程
为了实现预期的目的,将系统流程分为如下几个阶段:
1、使用官方 demo 移植 tflite 到 art-pi smart, 针对这部分内容可以查看文章 在 art-pi smart 上运行 tensorflow lite
2、移植 tensorflow 基础的图像分类 mnist 的 demo 到 art-pi smart,针对这部分内容可以查看文章
3、使用 kicad 设计 ov5640 转结板,并开发 ov5640 摄像头驱动,在开发这部分软件的过程中,遇到了问题,具体细节可以查看问题ov5640 显示效果不稳定
4、使用摄像头采集数据判断是否有车辆信息
本节重点描述系统流程的第 4 部分,训练自己的模型检测是否有车辆信息,这部分主要分为如下步骤:
1、从网上下载包含有车辆的图片数据集和没有车辆的数据集合(这部分内容,我选择了一些包含有花朵的数据集),通过 python 将其批量转换为屏幕分辨率的图片,这部分代码大概是这样的:
!/usr/bin/env python
源数据的目录
如果指定有源文件目录,使用指定的源文件目录
生成转换后的源文件的目录
最多转换 1000 张图片
修改原始图片的分辨率
for i in range(src_image_len):
current_image_name = src_image_lists[i]
full_current_image_name = os.path.join(web_pics, current_image_name)
target_image_name = current_image_name.split('.')[0]+'_convert.bmp'
full_target_image_name = os.path.join(taregt_pics, target_image_name)
raw_image =image.open(full_current_image_name)
image_l = raw_image.convert('l')
image = image_l.resize((480,272))
image.save(full_target_image_name)
print(np.array(image, dtype=np.float32, order=’c’).shape)
exit()
如图所示,四个目录分别是原始带有车辆和没有车辆的数据集目录和转换后的数据集目录。
2.标定带有车辆的图片和没有车辆的图片信息,使用 tensorflow 进行训练,这部分代码大概是这样的:
``` python
#!/usr/bin/env python
# 车标分类算法
from pil import image
import os
models_dir = 'models/'
if not os.path.exists(models_dir):
os.mkdir(models_dir)
model_tf = models_dir + 'model'
model_no_quant_tflite = models_dir + 'model_no_quant.tflite'
model_tflite = models_dir + 'model.tflite'
model_tflite_micro = models_dir + 'model.cc'
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
train_images_counts = 1000
whole_train_images = np.ones((2 * train_images_counts , 480, 272), dtype=np.float32)
whole_train_labels = np.ones((2 * train_images_counts , ), dtype=np.float32)
#test_images = np.ones((2 * test_images_counts , 480, 272), dtype=np.float32)
#test_labels = np.ones((2 * test_images_counts , ), dtype=np.float32)
car_convert_pics = 'cars_train_convert_sets'
flower_taregt_pics = 'flowers_convert_sets'
# 矩阵行列交换
def transpose_2d(data):
# transposed = list(zip(*data))
# [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
# 注意 zip 本身返回的数据类型为 tuple 元组
# 其中符号 * 号可以对元素进行解压或展开
transposed = list(map(list, zip(*data)))
return transposed
whole_train_sets_index = 0
def merge_whole_train_sets(src, type):
global whole_train_sets_index
src_image_lists = os.listdir(src)
for i in range(train_images_counts):
full_current_image_name = os.path.join(src, src_image_lists[i])
#print(full_current_image_name)
raw_image = image.open(full_current_image_name)
#print(type(raw_image.convert('rgb')))
temp_whole_train_images = np.array(raw_image, dtype=np.float32)
whole_train_images[whole_train_sets_index] = np.array(transpose_2d(temp_whole_train_images), dtype=np.float32)
whole_train_labels[whole_train_sets_index] = type
whole_train_sets_index = whole_train_sets_index + 1
merge_whole_train_sets(car_convert_pics, 1)
merge_whole_train_sets(flower_taregt_pics, 0)
print(whole_train_labels)
print(type(whole_train_images), whole_train_images.shape)
print(type(whole_train_labels), whole_train_labels.shape)
train_images, test_images = train_test_split(whole_train_images, train_size=0.8, random_state=10)
train_labels, test_labels = train_test_split(whole_train_labels, train_size=0.8, random_state=10)
print(type(train_images), type(train_labels))
print(train_images.shape, train_labels.shape)
class_names = ['nocar', 'car']
if false:
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(false)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
#exit()
#train_images = train_images
#test_images = test_images
#train_images = np.array(train_images, dtype=np.float32)
#plt.figure(figsize=(10,10))
#for i in range(25):
# plt.subplot(5,5,i+1)
# plt.xticks([])
# plt.yticks([])
# plt.grid(false)
# plt.imshow(train_images[i], cmap=plt.cm.binary)
# plt.xlabel(class_names[train_labels[i]])
#plt.show()
model = tf.keras.sequential([
tf.keras.layers.flatten(input_shape=(480, 272)),
tf.keras.layers.dense(128, activation='relu'),
tf.keras.layers.dense(2)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.sparsecategoricalcrossentropy(from_logits=true),
metrics=['accuracy'])
# 如果模型已经存在,加载整个模型
if os.path.exists(models_dir) and os.path.exists(model_tf) and 0 != len(os.listdir(model_tf)):
try:
#model.load_weights(model_tf + 'saved_model.pb')
model = keras.models.load_model(model_tf)
except:
print(load weights failed)
exit()
# 训练模型
else:
print(f{model_tf} no exist ?)
model.fit(train_images, train_labels, epochs=10)
# 查看 model 概要
print(model.summary())
# 测试模型
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(' test accuracy:', test_acc)
probability_model = tf.keras.sequential([model,
tf.keras.layers.softmax()])
predictions = probability_model.predict(test_images)
print(type(test_images), test_images.shape, red)
print(predictions[0])
#exit()
# 测试自定义图片
from pil import image
import sys
img_src = 'flowers/image_1111.jpg'
img_target = img_src.split('/')[-1].split('.')[0] + '_gry_test' + '.bmp'
print(img_target)
raw_image = image.open(img_src)
image = raw_image.resize((480, 272))
image_gray = image.convert('l')
image_gray_array = np.array(image_gray, dtype=np.float32)
image_gray_array = np.array(transpose_2d(image_gray_array), dtype=np.float32).reshape(1,480,272)
#image_gray_array = image_gray_array / 255.0
image_gray.save(img_target)
predictions = probability_model.predict(image_gray_array)
print(red prefictions)
print(predictions[0])
plt.figure()
plt.subplot(2,1,1)
plt.imshow(test_images[0], cmap=plt.cm.binary)
print(test_labels[0], oh no red)
plt.subplot(2,1,2)
plt.imshow(raw_image, cmap=plt.cm.binary)
plt.show()
#exit()
#plt.figure(figsize=(10,10))
#plt.xticks([])
#plt.yticks([])
#plt.grid(false)
#plt.imshow(test_images[0], cmap=plt.cm.binary)
#plt.show()
# save the model to disk
model.save(model_tf)
# convert the model to the tensorflow lite format without quantization
converter = tf.lite.tfliteconverter.from_saved_model(model_tf)
model_no_quant_tflite = converter.convert()
# save the model to disk
open(model_no_quant_tflite, wb).write(model_no_quant_tflite)
# convert the model to the tensorflow lite format with quantization
def representative_dataset():
for i in range(500):
# 强制转换为 float32 类型
array = np.array(train_images[i], dtype=np.float32)
#print(array.shape, red dbg)
#print(type(train_images[0].dtype), type(array[0].dtype), type(array), len(array))
yield([array])
# set the optimization flag.
converter.optimizations = [tf.lite.optimize.default]
# enforce integer only quantization
converter.target_spec.supported_ops = [tf.lite.opsset.tflite_builtins_int8]
converter.inference_input_type = tf.float32
converter.inference_output_type = tf.float32
# provide a representative dataset to ensure we quantize correctly.
converter.representative_dataset = representative_dataset
# 转换为 tflite 模型
model_tflite = converter.convert()
# save the model to disk
open(model_tflite, wb).write(model_tflite)
该函数可以训练模型导出 model.tflite 到 models 目录:
因为输入的 tensor 有 480*272 个,所以导致模型特别巨大,发现直接编译出的 rtthread.bin 有 16mb 左右,通过 tftp 下载后无法正常运行,就只能使用这个模型在 pc 端对 ov5640 采集的图片进行识别了。
1、开发 save_bmp.elf 工具,支持将当前显存的内容保存到 bmp 图片中,这部分代码大概这样,下述 demo 简单完成了使用显存内容对原始 bmp 图片的重写:
/*
* copyright (c) 2006-2022, rt-thread development team
*
* spdx-license-identifier: gpl-2.0
*
* change logs:
* date author notes
* 2022-05-05 iysheng the first version
*/
#include
#include
#includertdef.h
#include
#includert_lcd.h
typedefunsignedcharuint8_t;
typedefunsignedshortuint16_t;
typedefunsignedintuint32_t;
typedefintint32_t;
#define lcd_width 480
#define lcd_height 272
#define lcd_buf_size (lcd_width * lcd_height)
rt_uint16_t pixel_ptr[lcd_buf_size];
rt_device_t lcd = null;
struct fb_fix_screeninfo f_info;
struct fb_var_screeninfo v_info;
int rt_smart_lcdinit(void)
{
rt_err_t ret =-1;
lcd = rt_device_find(lcd);
if(!lcd)return1;
ret = rt_device_open(lcd, rt_device_oflag_rdwr);
if(-1==ret)return1;
rt_device_control(lcd, fbioget_fscreeninfo,&f_info);
printf(screen: %s - 0x%08x, size %d , f_info.id,(unsignedint)f_info.smem_start, f_info.smem_len);
rt_device_control(lcd, fbioget_vscreeninfo,&v_info);
printf(screen: bpp %d, width - %d, height - %d , v_info.bits_per_pixel, v_info.xres, v_info.yres);
return ret;
}
#pragma pack(1)
struct bmp_header {
uint16_t file_type;// file type always bm which is 0x4d42
uint32_t file_size;// size of the file (in bytes)
uint16_t reserved1;// reserved, always 0
uint16_t reserved2;// reserved, always 0
uint32_t offset_data;// start position of pixel data (bytes from the beginning of the file)
};
struct windows_bmp_info_header {
uint32_t size;// size of this header (in bytes)
int32_t width;// width of bitmap in pixels
int32_t height;// width of bitmap in pixels
uint16_t planes;// no. of planes for the target device, this is always 1
uint16_t bit_count;// no. of bits per pixel
uint32_t compression;// 0 or 3 - uncompressed. this program considers only uncompressed bmp images
uint32_t size_image;// 0 - for uncompressed images
int32_t x_pixels_per_meter;
int32_t y_pixels_per_meter;
uint32_t colors_used;// no. color indexes in the color table. use 0 for the max number of colors allowed by bit_count
uint32_t colors_important;// no. of colors used for displaying the bitmap. if 0 all colors are required
};
#define red_tflite_convert 10
int get_bmp_at(struct fb_fix_screeninfo *finfo,struct fb_var_screeninfo *vinfo,struct windows_bmp_info_header *header,uint8_t*buffer,uint8_t bytes)
{
int32_t x, y, i =0;
uint16_t pix_tmp =0;
vinfo->xres =0;
vinfo->yres =0;
for(y = header->height; y >0; y--)
{
for(x =0; x width; x++)
{
if(1== bytes)
{
buffer[i++]=*((uint16_t*)finfo->smem_start +(y -1+ vinfo->yres)* lcd_width + vinfo->xres + x);
}
elseif(2== bytes)
{
pix_tmp =*((uint16_t*)finfo->smem_start +(y -1+ vinfo->yres)* lcd_width + vinfo->xres + x);
buffer[i]= pix_tmp;
buffer[i +1]= pix_tmp >>8;
i +=2;
}
else
{
printf(error: no support this format );
return-1;
}
}
}
/* todo flush */
rt_device_control(lcd, red_tflite_convert, null);
return0;
}
void show_hex(uint8_t* buffer,uint16_t buffer_len,char*title)
{
uint16_t i =0;
printf([%s](%hu), title, buffer_len);
for(i =0; i >3, fp);
if(num != t_bmp_info_header.width * t_bmp_info_header.height * t_bmp_info_header.bit_count >>3)
{
printf(bmp raw data mismatch. );
return-5;
}
else
{
printf(save bmp ok);
fclose(fp);
}
return0;
}
2、实验,我使用了一个卡车模型进行采集,现场是这样的:
采集回来的图片是这样的:
隐约可以从这个灰度图中看出来卡车模型的轮廓,接下来使用 tflite 的模型对这个图片进行预测,结果可以看出来识别到这个图片中包含有车:
为了做对比,再采集一张有花朵的图片,进行预测,现场是这样的:
对摄像头采集的图片进行捕捉,保存到一个灰度 bmp 图片:
结果是:
可以看出正确识别除了是花还是汽车。
至此本次项目暂时告一段落了,通过这次试用,主要收获有两个方面:
1、通过实际对机器学习迁移到嵌入式设备端这个过程的接触,对在边缘节点进行机器学习有了一个基础的认识;
2、通过这次对 ov5640 摄像头的调试,对 csi 接口摄像头的图像采集以及显示有了一个更深入的理解;
目前还有部分未完成的工作,对摄像头采集的图像效果不是特别满意,目前分析可能是 art-pi smart 到转接板之间排线有点长(我选的是10cm的)对显示信号(有高频 50mhz 附近的 pclk 时钟)有干扰,转接板没有处理好高频信号导致的,看一下转接板 pcb 和 3d 是这样的。
开口式霍尔电流传感器帮助直流配电系统智能改造
华为总裁表示排除华为将破坏公平竞争并导致极为负面的影响
中国移动宣布政企客户总数累计已突破718万服务集团成员数超过2.8亿
多普光电:销售额已超过1.1亿,营收同比大幅增长
太阳能电池特性
在ART-Pi Smart上对摄像头采集的数据进行车标识别
美国宣布将在印度建造六座核电站
人工智能是物理安防的破坏者?
拓维信息打通企业业务全经营链条 提高业务效率
新产品包:配备Oryx摄像头+Myricom卡,可靠的10GigE性能,经济实惠
避免受制于人 国产医疗器械技术急需创新突破
vivoX9磨砂黑来袭!网友问:会超越OPPO新年红爆款么?
箱式变压器的优缺点是什么_箱式变压器的作用是什么
新能源汽车高销量下,动力电池技术和产业大有可为
汽车产业互联网的下一步是产业整合提升效率的阶段
3D全息投影沙盘有什么特点
功率器件上市公司中报披露,高增长,发力新能源
为双输出电源添加看门狗
华为麒麟芯片回归,魅族用实际行动欢迎Mate回归
STM32F207是如何将25M晶振时钟转换为120M系统主频时钟的?