1. 新建文件夹caffe/data/myself/;
2. 继续在myself文件夹下新建两个文件夹:caffe/data/myself/train,caffe/data/myself/val;
3. 在train文件夹下放需要转换格式的训练图像集,在val文件夹中放val图像集;
4. 图像大小可能不符合设计神经网络的输入要求,需要将图像resize一下。如手写字符识别是28*28,这里以256*256大小为例,注意将图像途径改为自己的,后缀也要注意和自己的对应;
$ for name in /path/to/imagenet/val/*.JPEG; do
convert -resize 256x256\! $name $name
done
执行命令后的效果如下,查看cat-0.jpg的大小,发现已经变为256*256:
5. 样本数据较小,可以手动做分类标签:在caffe/data/myself/文件夹下新建train.txt;照片路径+类别;
样本较多时,编写指令批量处理【这里没有做功课】,参考别人的命令:
find -name *.jpeg |cut -d '/' -f2-3> train.txt;
6. 新建文件夹caffe/examples/myself/,将caffe/examples/imagenet的create_imagenet.sh复制到该文件夹下,将其名改为create_animal.sh,修改训练和测试路径的设置,如图:
代码如下:
#!/usr/bin/env sh
# Create the imagenet lmdb inputs
# N.B. set the path to the imagenet train + val data dirs
set -e
EXAMPLE=examples/myself
DATA=data/myself
TOOLS=build/tools
TRAIN_DATA_ROOT=/home/sz/caffe/data/myself/train/
VAL_DATA_ROOT=/home/sz/caffe/data/myself/val/
# Set RESIZE=true to resize the images to 256x256. Leave as false if images have
# already been resized using another tool.
RESIZE=false
if $RESIZE; then
RESIZE_HEIGHT=28
RESIZE_WIDTH=28
else
RESIZE_HEIGHT=0
RESIZE_WIDTH=0
fi
if [ ! -d "$TRAIN_DATA_ROOT" ]; then
echo "Error: TRAIN_DATA_ROOT is not a path to a directory: $TRAIN_DATA_ROOT"
echo "Set the TRAIN_DATA_ROOT variable in create_imagenet.sh to the path" \
"where the ImageNet training data is stored."
exit 1
fi
if [ ! -d "$VAL_DATA_ROOT" ]; then
echo "Error: VAL_DATA_ROOT is not a path to a directory: $VAL_DATA_ROOT"
echo "Set the VAL_DATA_ROOT variable in create_imagenet.sh to the path" \
"where the ImageNet validation data is stored."
exit 1
fi
echo "Creating train lmdb..."
GLOG_logtostderr=1 $TOOLS/convert_imageset \
--resize_height=$RESIZE_HEIGHT \
--resize_width=$RESIZE_WIDTH \
--shuffle \
$TRAIN_DATA_ROOT \
$DATA/train.txt \
$EXAMPLE/myself_train_lmdb
echo "Creating val lmdb..."
GLOG_logtostderr=1 $TOOLS/convert_imageset \
--resize_height=$RESIZE_HEIGHT \
--resize_width=$RESIZE_WIDTH \
--shuffle \
--gray \
$VAL_DATA_ROOT \
$DATA/val.txt \
$EXAMPLE/myself_val_lmdb
echo "Done."
注意其中的代码段:
GLOG_logtostderr=1 $TOOLS/convert_imageset \
--resize_height=$RESIZE_HEIGHT \
--resize_width=$RESIZE_WIDTH \
--shuffle \
-gray: 是否以灰度图的方式打开图片。程序调用opencv库中的imread()函数来打开图片,默认为false
-backend:需要转换成的db文件格式,可选为leveldb或lmdb,默认为lmdb
-check_size: 检查所有的数据是否有相同的尺寸。默认为false,不检查
-encoded: 是否将原图片编码放入最终的数据中,默认为false
-encode_type: 与前一个参数对应,将图片编码为哪一个格式:‘png','jpg'......
7. 运行该sh文件【注意一定要在caffe下运行,由于sh文件中TOOLS=build/tools,build文件夹是在caffe下的!】:
$ cd caffe
$ ./examples/myself/create_animal.sh
运行结果如下:
查看caffe/examples/myself/文件夹,得到myself_train_lmdb和myself_val_lmdb: