本教程将带你实现一个实时手势猜拳游戏识别系统,使用Kaggle公开的「Rock-Paper-Scissors」数据集(包含石头、剪刀、布三种手势),全程仅需CPU即可运行。最终效果可通过摄像头实时识别手势,并与电脑进行猜拳对战!
打开Pycharm,新建项目文件夹
安装所需依赖库
# 安装所需库(Python 3.8+)
pip install numpy matplotlib opencv-python tensorflow-cpu
使用TensorFlow Datasets内置的「Rock-Paper-Scissors」数据集:
import tensorflow as tf
import tensorflow_datasets as tfds
# 自动下载数据集(首次运行需要等待)
dataset, info = tfds.load('rock_paper_scissors',
split=['train', 'test'],
as_supervised=True,
with_info=True,
shuffle_files=True)
# 提取训练集和测试集
train_ds, test_ds = dataset[0], dataset[1]
# 查看数据集信息
print(f"训练集样本数: {
info.splits['train'].num_examples}")
print(f"测试集样本数: {
info.splits['test'].num_examples}")
def preprocess(image, label):
# 统一尺寸 + 归一化
image = tf.image.resize(image, (150, 150))
image = tf.image.rgb_to_grayscale(image) # 转为灰度图减少计算量
return image/255.0, label
# 配置数据管道
BATCH_SIZE