基于遥感小目标XView数据集来实现一个目标检测任务——
遥感小目标Xview原始目标检测数据集
数据集已经包括60个类别
数据集是txt和json格式
数据集已划分为训练集/验证集
yolo可用
相关Faster RCNN/Cascade RCNN/SSD/Retinant模型也可
以下文章代码仅供参考:
基于遥感小目标XView数据集来实现一个目标检测任务。为了简化流程,选择YOLOv5作为目标检测模型,并使用PyTorch框架进行实现。以下是详细的步骤:
环境准备
确保您已经安装了以下软件和库:
- Python 3.8 或更高版本
- PyTorch 1.9 或更高版本
- torchvision 0.10 或更高版本
- OpenCV
- numpy
- pandas
- matplotlib
- albumentations(用于数据增强)
您可以使用以下命令安装所需的Python库:
pipinstalltorch torchvision opencv-python numpy pandas matplotlib albumentations数据集准备
假设您的数据集已经按照YOLO格式组织好,并且包含训练集和验证集。如果还没有转换为YOLO格式,我们需要先进行数据转换。
数据集结构
datasets/ ├── xview/ │ ├── images/ │ │ ├── train/ │ │ └── val/ │ └── labels/ │ ├── train/ │ └── val/ └── xview_classes.txtxview_classes.txt文件包含60个类别的名称,每行一个类别名称。
数据转换脚本
如果您的数据集是JSON格式,可以使用以下脚本来将其转换为YOLO格式的TXT文件。假设JSON文件中包含边界框信息和类别标签。
[<title="Convert JSON to YOLO Format">]importjsonimportosfrompathlibimportPathimportcv2defconvert_json_to_yolo(json_file,output_dir,image_dir):withopen(json_file,'r')asf:data=json.load(f)categories={category['id']:category['name']forcategoryindata['categories']}class_names=sorted(categories.values())class_dict={class_name:idxforidx,class_nameinenumerate(class_names)}withopen(output_dir/'classes.txt','w')asf:forclass_nameinclass_names:f.write(f'{class_name}\n')forannotationindata['annotations']:img_id=annotation['image_id']bbox=annotation['bbox']category_id=annotation['category_id']image_info=next(itemforitemindata['images']ifitem['id']==img_id)image_path=image_dir/image_info['file_name']width,height=image_info['width'],image_info['height']label_path=output_dir/'labels'/(Path(image_info['file_name']).stem+'.txt')withopen(label_path,'a')asf:class_idx=class_dict[categories[category_id]]x_center=(bbox[0]+bbox[2]/2)/width y_center=(bbox[1]+bbox[3]/2)/height w=bbox[2]/width h=bbox[3]/height f.write(f'{class_idx}{x_center}{y_center}{w}{h}\n')# Example usagejson_file='path/to/xview/annotations.json'output_dir=Path('datasets/xview/')image_dir=Path('path/to/xview/images/train/')# Change to 'val/' for validation setconvert_json_to_yolo(json_file,output_dir,image_dir)模型训练
我们将使用YOLOv5进行训练。首先,克隆YOLOv5仓库并设置环境。
gitclone https://github.com/ultralytics/yolov5.gitcdyolov5 pipinstall-rrequirements.txt准备配置文件
创建一个hyp.scratch.yaml文件来定义超参数:
# Hyperparameters for YOLOv5 training from scratchlr0:0.01# initial learning rate (SGD=1E-2, Adam=1E-3)lrf:0.1# final OneCycleLR learning rate (lr0 * lrf)momentum:0.937# SGD momentum/Adam beta1weight_decay:0.0005# optimizer weight decay 5e-4warmup_epochs:3.0# warmup epochs (fractions ok)warmup_momentum:0.8# warmup initial momentumwarmup_bias_lr:0.1# warmup initial bias lrbox:0.05# box loss gaincls:0.5# cls loss gaincls_pw:1.0# cls BCELoss positive_weightobj:1.0# obj loss gain (scale with pixels)obj_pw:1.0# obj BCELoss positive_weightiou_t:0.20# IoU training thresholdanchor_t:4.0# anchor-multiple thresholdfl_gamma:0.0# focal loss gamma (efficientDet default gamma=1.5)hsv_h:0.015# image HSV-Hue augmentation (fraction)hsv_s:0.7# image HSV-Saturation augmentation (fraction)hsv_v:0.4# image HSV-Value augmentation (fraction)degrees:0.0# image rotation (+/- deg)translate:0.1# image translation (+/- fraction)scale:0.5# image scale (+/- gain)shear:0.0# image shear (+/- deg)perspective:0.0# image perspective (+/- fraction), range 0-0.001flipud:0.0# image flip up-down (probability)fliplr:0.5# image flip left-right (probability)mosaic:1.0# image mosaic (probability)mixup:0.0# image mixup (probability)copy_paste:0.0# segment copy-paste (probability)paste_in:0.0# segment paste-in (probability)rect:0# rectangular trainingresume:false# resume training from last checkpointnosave:false# only save final checkpointnoval:false# only validate final epochnoautoanchor:true# disable AutoAnchorevolve:false# evolve hyperparametersbucket:''# gsutil bucketcache_images:false# cache images for faster trainingimage_weights:false# use weighted image selection for trainingsingle_cls:false# train multi-class data as single-classoptimizer:SGD# optimizer: SGD or AdamWsync_bn:false# use SyncBatchNorm, only available in DDP modeworkers:8# dataloader workers (max is number of CPU cores)freeze:0# freeze first n layersv5_metric:true# assume maximum recall as 1.0 in AP calculationmulti_scale:true# vary input size between 320 and 640 pixelsrect_training:false# rectangular trainingcos_lr:false# cosine LR schedulerclose_mosaic:1000# close mosaic borderscales:[0.5,1.5]# image size scalesaugment:true# augment dataverbose:false# verbose printseed:0# random seed for reproducibilitylocal_rank:-1# ddp device id (-1 for single gpu train)entity:null# W&B entityupload_dataset:False# upload dataset as W&B artifact tablebbox_interval:-1# W&B bounding box logging intervalartifact_alias:latest# version of dataset artifact to useproject:runs/train# save results to project/nameexist_ok:false# existing project/name ok, do not incrementquad:false# quadrilateral anchorslinear_assignment:false# use linear assignment for NMS创建一个data.yaml文件来定义数据集路径和类别:
train:../datasets/xview/images/train/val:../datasets/xview/images/val/nc:60# number of classesnames:['class1','class2',...,'class60']# list of class names将names字段替换为实际的类别名称。
训练模型
使用以下命令开始训练:
python train.py--img640--batch16--epochs50--datadata.yaml--cfgyolov5s.yaml--weightsyolov5s.pt--hyphyp.scratch.yaml结果评估
训练完成后,可以使用以下命令评估模型性能:
python val.py--datadata.yaml--weightsruns/train/exp/weights/best.pt--tasktest使用说明
配置路径:
- 确保
datasets/xview/目录结构正确。 - 确保
data.yaml中的路径和类别名称正确。
- 确保
运行脚本:
- 在终端中依次运行数据转换脚本、训练脚本和评估脚本。
注意事项:
- 根据需要调整超参数和训练设置。
- 可以通过修改
data.yaml中的cfg参数来选择不同的YOLOv5模型架构(如yolov5m.yaml,yolov5l.yaml,yolov5x.yaml)。
示例
假设您的数据集文件夹结构如下:
datasets/ └── xview/ ├── annotations.json ├── images/ │ ├── train/ │ └── val/ └── labels/ ├── train/ └── val/并且annotations.json包含所有必要的注释信息。运行上述脚本后,您可以查看训练日志和最终的模型权重文件。
总结
通过上述步骤,我们可以构建一个全面的目标检测系统,包括数据集准备、数据转换、模型训练和结果评估。以下是所有相关的代码文件:
- 数据转换脚本(
convert_json_to_yolo.py) - YOLOv5超参数配置文件(
hyp.scratch.yaml) - YOLOv5数据集配置文件(
data.yaml)