怎么做qq二维码网站,系部 网站建设方案,建设外贸网站案例,贵州企业网站若该文为原创文章#xff0c;转载请注明原文出处。 一、简介
人工智能的发展日新月异#xff0c;也深刻的影响到人机交互领域的发展。手势动作作为一种自然、快捷的交互方式#xff0c;在智能驾驶、虚拟现实等领域有着广泛的应用。手势识别的任务是#xff0c;当操作者做出…若该文为原创文章转载请注明原文出处。 一、简介
人工智能的发展日新月异也深刻的影响到人机交互领域的发展。手势动作作为一种自然、快捷的交互方式在智能驾驶、虚拟现实等领域有着广泛的应用。手势识别的任务是当操作者做出某个手势动作后计算机能够快速准确的判断出该手势的类型。本文将使用ModelArts开发训练一个视频动态手势识别的算法模型对上滑、下滑、左滑、右滑、打开、关闭等动态手势类别进行检测实现类似隔空手势的功能。
在前面也有使用mediapipe实现类似功能。具体自行参考。
本文章参考CNN-VIT 视频动态手势识别【玩转华为云】-云社区-华为云 二、环境
使用的是AUTODL配置如下
镜像PyTorch 1.7.0 Python 3.8(ubuntu18.04) Cuda 11.0
GPU RTX 2080 Ti(11GB) * 1升降配置
CPU12 vCPU Intel(R) Xeon(R) Platinum 8255C CPU 2.50GHz
三、环境搭建
1、创建虚拟环境
conda create -n cnn_hand_gesture_env python3.8
2、激活
conda activate cnn_hand_gesture_env
3、安装依赖项
conda install cudatoolkit11.3.1 cudnn8.2.1 -y --override-channels --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main pip install tensorflow-gpu2.5.0 -i https://pypi.doubanio.com/simple --userpip install opencv-contrib-python
pip install imageio
pip install imgaug
pip install tqdm
pip install IPythonpip install numpy1.19.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install matplotlib3.6
这里需要注意的是numpy版本和matplotlib版本,tensorflow2.5版本对应的numpy版本是1.19.3
如果版本过高会一直出错错误。
四、数据下载
下载数据使用的是华为云可以自行下载或联系我。
import os
import moxing as moxif not os.path.exists(hand_gesture):mox.file.copy_parallel(obs://modelbox-course/hand_gesture, hand_gesture)
五、算法简介
视频动态手势识别算法首先使用预训练网络InceptionResNetV2逐帧提取视频动作片段特征然后输入Transformer Encoder进行分类。我们使用动态手势识别样例数据集对算法进行测试总共包含108段视频数据集包含无效手势、上滑、下滑、左滑、右滑、打开、关闭等7种手势的视频具体操作流程如下 六、流程
1、将采集的视频文件解码抽取关键帧每隔4帧保存一次然后对图像进行中心裁剪和预处理
2、创建图像特征提取器使用预训练模型InceptionResNetV2提取图像特征
3、提取视频特征向量如果视频不足40帧就创建全0数组进行补白
4、创建VIT Mode
5、视频推理
6、加载VIT Model获取视频类别索引标签
7、使用图像特征提取器InceptionResNetV2提取视频特征
8、将视频序列的特征向量输入Transformer Encoder进行预测
9、打印模型预测结果
七、测试 Autodl自带有JupyterLab, 直接运行一遍。
代码解析
1、创建视频输入管道获取视频类别标签
videos glob.glob(hand_gesture/*.mp4)
np.random.shuffle(videos)
labels [int(video.split(_)[-2]) for video in videos]
videos[:5], len(videos), labels[:5], len(videos)
2、视频抽帧预处理
def load_video(file_name):cap cv2.VideoCapture(file_name) # 每隔多少帧抽取一次frame_interval 4frames []count 0while True:ret, frame cap.read()if not ret:break# 每隔frame_interval帧保存一次if count % frame_interval 0:# 中心裁剪 frame crop_center_square(frame)# 缩放frame cv2.resize(frame, (IMG_SIZE, IMG_SIZE))# BGR - RGB [0,1,2] - [2,1,0]frame frame[:, :, [2, 1, 0]]frames.append(frame)count 1return np.array(frames)
3、创建图像特征提取器
def get_feature_extractor():feature_extractor keras.applications.inception_resnet_v2.InceptionResNetV2(weights imagenet,include_top False,pooling avg,input_shape (IMG_SIZE, IMG_SIZE, 3))preprocess_input keras.applications.inception_resnet_v2.preprocess_inputinputs keras.Input((IMG_SIZE, IMG_SIZE, 3))preprocessed preprocess_input(inputs)outputs feature_extractor(preprocessed)model keras.Model(inputs, outputs, name feature_extractor)return model
4、提取视频图像特征
def load_data(videos, labels):video_features []for video in tqdm(videos):frames load_video(video)counts len(frames)# 如果帧数小于MAX_SEQUENCE_LENGTHif counts MAX_SEQUENCE_LENGTH:# 补白diff MAX_SEQUENCE_LENGTH - counts# 创建全0的numpy数组padding np.zeros((diff, IMG_SIZE, IMG_SIZE, 3))# 数组拼接frames np.concatenate((frames, padding))# 获取前MAX_SEQUENCE_LENGTH帧画面frames frames[:MAX_SEQUENCE_LENGTH, :]# 批量提取特征video_feature feature_extractor.predict(frames)video_features.append(video_feature)return np.array(video_features), np.array(labels)
5、编码器
# 编码器
class TransformerEncoder(layers.Layer):def __init__(self, num_heads, embed_dim):super().__init__()self.p_embedding PositionalEmbedding(MAX_SEQUENCE_LENGTH, NUM_FEATURES)self.attention layers.MultiHeadAttention(num_headsnum_heads, key_dimembed_dim, dropout0.1)self.layernorm layers.LayerNormalization()def call(self,x):# positional embeddingpositional_embedding self.p_embedding(x)# self attentionattention_out self.attention(query positional_embedding,value positional_embedding,key positional_embedding,attention_mask None)# layer norm with residual connection output self.layernorm(positional_embedding attention_out)return output
6、训练模式
history model.fit(train_dataset,epochs 1000,steps_per_epoch train_count // batch_size, validation_steps test_count // batch_size, validation_data test_dataset,callbacks [checkpoint, earlyStopping, rlp])
7、测试
# 视频预测
def testVideo():test_file random.sample(videos, 1)[0]label test_file.split(_)[-2]print(文件名:{}.format(test_file) )print(真实类别:{}.format(label_to_name.get(int(label))) )# 读取视频每一帧frames load_video(test_file)# 挑选前帧MAX_SEQUENCE_LENGTH显示frames frames[:MAX_SEQUENCE_LENGTH].astype(np.uint8)# 保存为GIFimageio.mimsave(animation.gif, frames, duration10)# 获取特征feat getVideoFeat(frames)# 模型推理prob model.predict(tf.expand_dims(feat, axis0))[0]print(预测类别)for i in np.argsort(prob)[::-1][:5]:print({}: {}%.format(label_to_name[i], round(prob[i]*100, 2)))#return display(Image(open(animation.gif, rb).read()))
8、源码
import cv2
import glob
import numpy as np
from tqdm import tqdm
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as pltfrom collections import Counter
import random
import imageio
from IPython.display import Imagefrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau#%matplotlib inlineMAX_SEQUENCE_LENGTH 40
IMG_SIZE 299
NUM_FEATURES 1536# 图像中心裁剪
def crop_center_square(img):h, w img.shape[:2]square_w min(h, w)start_x w // 2 - square_w // 2end_x start_x square_wstart_y h // 2 - square_w // 2end_y start_y square_wresult img[start_y:end_y, start_x:end_x]return result# 视频抽帧预处理
def load_video(file_name):cap cv2.VideoCapture(file_name) # 每隔多少帧抽取一次frame_interval 4frames []count 0while True:ret, frame cap.read()if not ret:break# 每隔frame_interval帧保存一次if count % frame_interval 0:# 中心裁剪 frame crop_center_square(frame)# 缩放frame cv2.resize(frame, (IMG_SIZE, IMG_SIZE))# BGR - RGB [0,1,2] - [2,1,0]frame frame[:, :, [2, 1, 0]]frames.append(frame)count 1return np.array(frames) # 创建图像特征提取器
def get_feature_extractor():feature_extractor keras.applications.inception_resnet_v2.InceptionResNetV2(weights imagenet,include_top False,pooling avg,input_shape (IMG_SIZE, IMG_SIZE, 3))preprocess_input keras.applications.inception_resnet_v2.preprocess_inputinputs keras.Input((IMG_SIZE, IMG_SIZE, 3))preprocessed preprocess_input(inputs)outputs feature_extractor(preprocessed)model keras.Model(inputs, outputs, name feature_extractor)return model# 提取视频图像特征
def load_data(videos, labels):video_features []for video in tqdm(videos):frames load_video(video)counts len(frames)# 如果帧数小于MAX_SEQUENCE_LENGTHif counts MAX_SEQUENCE_LENGTH:# 补白diff MAX_SEQUENCE_LENGTH - counts# 创建全0的numpy数组padding np.zeros((diff, IMG_SIZE, IMG_SIZE, 3))# 数组拼接frames np.concatenate((frames, padding))# 获取前MAX_SEQUENCE_LENGTH帧画面frames frames[:MAX_SEQUENCE_LENGTH, :]# 批量提取特征video_feature feature_extractor.predict(frames)video_features.append(video_feature)return np.array(video_features), np.array(labels)# 位置编码
class PositionalEmbedding(layers.Layer):def __init__(self, seq_length, output_dim):super().__init__()# 构造从0~MAX_SEQUENCE_LENGTH的列表self.positions tf.range(0, limitMAX_SEQUENCE_LENGTH)self.positional_embedding layers.Embedding(input_dimseq_length, output_dimoutput_dim)def call(self,x):# 位置编码positions_embedding self.positional_embedding(self.positions)# 输入相加return x positions_embedding# 编码器
class TransformerEncoder(layers.Layer):def __init__(self, num_heads, embed_dim):super().__init__()self.p_embedding PositionalEmbedding(MAX_SEQUENCE_LENGTH, NUM_FEATURES)self.attention layers.MultiHeadAttention(num_headsnum_heads, key_dimembed_dim, dropout0.1)self.layernorm layers.LayerNormalization()def call(self,x):# positional embeddingpositional_embedding self.p_embedding(x)# self attentionattention_out self.attention(query positional_embedding,value positional_embedding,key positional_embedding,attention_mask None)# layer norm with residual connection output self.layernorm(positional_embedding attention_out)return outputdef video_cls_model(class_vocab):# 类别数量classes_num len(class_vocab)# 定义模型model keras.Sequential([layers.InputLayer(input_shape(MAX_SEQUENCE_LENGTH, NUM_FEATURES)),TransformerEncoder(2, NUM_FEATURES),layers.GlobalMaxPooling1D(),layers.Dropout(0.1),layers.Dense(classes_num, activationsoftmax)])# 编译模型model.compile(optimizer keras.optimizers.Adam(1e-5), loss keras.losses.SparseCategoricalCrossentropy(from_logitsFalse),metrics [accuracy])return model# 获取视频特征
def getVideoFeat(frames):frames_count len(frames)# 如果帧数小于MAX_SEQUENCE_LENGTHif frames_count MAX_SEQUENCE_LENGTH:# 补白diff MAX_SEQUENCE_LENGTH - frames_count# 创建全0的numpy数组padding np.zeros((diff, IMG_SIZE, IMG_SIZE, 3))# 数组拼接frames np.concatenate((frames, padding))# 取前MAX_SEQ_LENGTH帧frames frames[:MAX_SEQUENCE_LENGTH,:]# 计算视频特征 N, 1536video_feat feature_extractor.predict(frames)return video_feat# 视频预测
def testVideo():test_file random.sample(videos, 1)[0]label test_file.split(_)[-2]print(文件名:{}.format(test_file) )print(真实类别:{}.format(label_to_name.get(int(label))) )# 读取视频每一帧frames load_video(test_file)# 挑选前帧MAX_SEQUENCE_LENGTH显示frames frames[:MAX_SEQUENCE_LENGTH].astype(np.uint8)# 保存为GIFimageio.mimsave(animation.gif, frames, duration10)# 获取特征feat getVideoFeat(frames)# 模型推理prob model.predict(tf.expand_dims(feat, axis0))[0]print(预测类别)for i in np.argsort(prob)[::-1][:5]:print({}: {}%.format(label_to_name[i], round(prob[i]*100, 2)))#return display(Image(open(animation.gif, rb).read()))if __name__ __main__:print(Tensorflow version: {}.format(tf.__version__))print(GPU available: {}.format(tf.config.list_physical_devices(GPU)))# 创建视频输入管道获取视频类别标签videos glob.glob(hand_gesture/*.mp4)np.random.shuffle(videos)labels [int(video.split(_)[-2]) for video in videos]videos[:5], len(videos), labels[:5], len(videos)print(labels)# 显示数据分布情况counts Counter(labels)print(counts)plt.figure(figsize(8, 4))plt.bar(counts.keys(), counts.values())plt.xlabel(Class label)plt.ylabel(Number of samples)plt.title(Class distribution in videos)plt.show()# 显示视频label_to_name {0:无效手势, 1:上滑, 2:下滑, 3:左滑, 4:右滑, 5:打开, 6:关闭, 7:放大, 8:缩小}print(label_to_name.get(labels[0]))frames load_video(videos[0])frames frames[:MAX_SEQUENCE_LENGTH].astype(np.uint8)imageio.mimsave(test.gif, frames, durations10)print(mim save test.git)#display(Image(open(test.gif, rb).read()))#frames.shapeprint(frames.shape)feature_extractor get_feature_extractor()feature_extractor.summary()video_features, classes load_data(videos, labels)video_features.shape, classes.shapeprint(video_features.shape)print(classes.shape)# Datasetbatch_size 16dataset tf.data.Dataset.from_tensor_slices((video_features, classes))dataset dataset.shuffle(len(videos))test_count int(len(videos) * 0.2)train_count len(videos) - test_countdataset_train dataset.skip(test_count).cache().repeat()dataset_test dataset.take(test_count).cache().repeat()train_dataset dataset_train.shuffle(train_count).batch(batch_size)test_dataset dataset_test.shuffle(test_count).batch(batch_size)train_dataset, train_count, test_dataset, test_countprint(train_dataset)print(train_count)print(test_dataset)print(test_count)# 模型实例化model video_cls_model(np.unique(labels))# 打印模型结构model.summary()# 保存检查点checkpoint ModelCheckpoint(filepathbest.h5, monitorval_loss, save_weights_onlyTrue, save_best_onlyTrue, verbose1, modemin)# 提前终止earlyStopping EarlyStopping(monitorloss, patience50, modemin, baselineNone)# 减少learning raterlp ReduceLROnPlateau(monitorloss, factor0.7, patience30, min_lr1e-15, modemin, verbose1)# 开始训练history model.fit(train_dataset,epochs 1000,steps_per_epoch train_count // batch_size, validation_steps test_count // batch_size, validation_data test_dataset,callbacks [checkpoint, earlyStopping, rlp])# 绘制结果plt.plot(history.epoch, history.history[loss], r, labelloss)plt.plot(history.epoch, history.history[val_loss], g--, labelval_loss)plt.title(VIT Model)plt.xlabel(Epoch)plt.ylabel(Loss)plt.legend()plt.plot(history.epoch, history.history[accuracy], r, labelacc)plt.plot(history.epoch, history.history[val_accuracy], g--, labelval_acc)plt.title(VIT Model)plt.xlabel(Epoch)plt.ylabel(Accuracy)plt.legend()# 加载训练最优权重model.load_weights(best.h5)# 模型评估model.evaluate(dataset.batch(batch_size))# 保存模型model.save(saved_model)print(save model)# 手势识别# 加载模型model tf.keras.models.load_model(saved_model)# 类别标签label_to_name {0:无效手势, 1:上滑, 2:下滑, 3:左滑, 4:右滑, 5:打开, 6:关闭, 7:放大, 8:缩小}# 视频推理for i in range(20):testVideo()
运行后会训练模型 并保存模型测试
测试结果 如有侵权或需要完整代码请及时联系博主。 文章转载自: http://www.morning.ftcrt.cn.gov.cn.ftcrt.cn http://www.morning.lyhry.cn.gov.cn.lyhry.cn http://www.morning.mumgou.com.gov.cn.mumgou.com http://www.morning.jpwmk.cn.gov.cn.jpwmk.cn http://www.morning.sqgsx.cn.gov.cn.sqgsx.cn http://www.morning.bzlgb.cn.gov.cn.bzlgb.cn http://www.morning.c7512.cn.gov.cn.c7512.cn http://www.morning.xnhnl.cn.gov.cn.xnhnl.cn http://www.morning.dfffm.cn.gov.cn.dfffm.cn http://www.morning.pmjw.cn.gov.cn.pmjw.cn http://www.morning.cpktd.cn.gov.cn.cpktd.cn http://www.morning.wfspn.cn.gov.cn.wfspn.cn http://www.morning.phxns.cn.gov.cn.phxns.cn http://www.morning.jxfmn.cn.gov.cn.jxfmn.cn http://www.morning.fkmqg.cn.gov.cn.fkmqg.cn http://www.morning.jcxqc.cn.gov.cn.jcxqc.cn http://www.morning.nzsx.cn.gov.cn.nzsx.cn http://www.morning.ndhxn.cn.gov.cn.ndhxn.cn http://www.morning.tpxgm.cn.gov.cn.tpxgm.cn http://www.morning.rmltt.cn.gov.cn.rmltt.cn http://www.morning.cgbgc.cn.gov.cn.cgbgc.cn http://www.morning.rdkt.cn.gov.cn.rdkt.cn http://www.morning.sbwr.cn.gov.cn.sbwr.cn http://www.morning.bsrp.cn.gov.cn.bsrp.cn http://www.morning.dwztj.cn.gov.cn.dwztj.cn http://www.morning.trhrk.cn.gov.cn.trhrk.cn http://www.morning.kczkq.cn.gov.cn.kczkq.cn http://www.morning.xnymt.cn.gov.cn.xnymt.cn http://www.morning.flqkp.cn.gov.cn.flqkp.cn http://www.morning.nqmkr.cn.gov.cn.nqmkr.cn http://www.morning.xwzsq.cn.gov.cn.xwzsq.cn http://www.morning.zsyqg.cn.gov.cn.zsyqg.cn http://www.morning.xbckm.cn.gov.cn.xbckm.cn http://www.morning.wmmjw.cn.gov.cn.wmmjw.cn http://www.morning.nzcys.cn.gov.cn.nzcys.cn http://www.morning.lfqtp.cn.gov.cn.lfqtp.cn http://www.morning.ypcbm.cn.gov.cn.ypcbm.cn http://www.morning.qnzk.cn.gov.cn.qnzk.cn http://www.morning.ssqwr.cn.gov.cn.ssqwr.cn http://www.morning.zhffz.cn.gov.cn.zhffz.cn http://www.morning.ykyfq.cn.gov.cn.ykyfq.cn http://www.morning.qqrqb.cn.gov.cn.qqrqb.cn http://www.morning.gcdzp.cn.gov.cn.gcdzp.cn http://www.morning.hhqtq.cn.gov.cn.hhqtq.cn http://www.morning.whpsl.cn.gov.cn.whpsl.cn http://www.morning.ykwgl.cn.gov.cn.ykwgl.cn http://www.morning.ndpzm.cn.gov.cn.ndpzm.cn http://www.morning.hpmzs.cn.gov.cn.hpmzs.cn http://www.morning.phechi.com.gov.cn.phechi.com http://www.morning.nfccq.cn.gov.cn.nfccq.cn http://www.morning.hbtarq.com.gov.cn.hbtarq.com http://www.morning.xlyt.cn.gov.cn.xlyt.cn http://www.morning.qywfw.cn.gov.cn.qywfw.cn http://www.morning.lltdf.cn.gov.cn.lltdf.cn http://www.morning.zxqyd.cn.gov.cn.zxqyd.cn http://www.morning.lfdmf.cn.gov.cn.lfdmf.cn http://www.morning.cfnsn.cn.gov.cn.cfnsn.cn http://www.morning.tnhqr.cn.gov.cn.tnhqr.cn http://www.morning.gbsfs.com.gov.cn.gbsfs.com http://www.morning.lszjq.cn.gov.cn.lszjq.cn http://www.morning.kpxnz.cn.gov.cn.kpxnz.cn http://www.morning.nktxr.cn.gov.cn.nktxr.cn http://www.morning.rknhd.cn.gov.cn.rknhd.cn http://www.morning.xnymt.cn.gov.cn.xnymt.cn http://www.morning.jzkqg.cn.gov.cn.jzkqg.cn http://www.morning.dshxj.cn.gov.cn.dshxj.cn http://www.morning.pljxz.cn.gov.cn.pljxz.cn http://www.morning.nmhpq.cn.gov.cn.nmhpq.cn http://www.morning.bxdlrcz.cn.gov.cn.bxdlrcz.cn http://www.morning.nwfpl.cn.gov.cn.nwfpl.cn http://www.morning.bksbx.cn.gov.cn.bksbx.cn http://www.morning.cplym.cn.gov.cn.cplym.cn http://www.morning.bpmth.cn.gov.cn.bpmth.cn http://www.morning.sjgsh.cn.gov.cn.sjgsh.cn http://www.morning.jfqqs.cn.gov.cn.jfqqs.cn http://www.morning.dbddm.cn.gov.cn.dbddm.cn http://www.morning.kybjr.cn.gov.cn.kybjr.cn http://www.morning.llthz.cn.gov.cn.llthz.cn http://www.morning.kklwz.cn.gov.cn.kklwz.cn http://www.morning.zgdnd.cn.gov.cn.zgdnd.cn