利用halcon的深度学习网络进行目标检测

halcon深度学习

  • 1.halcon目标检测总工作流程:
    • 准备工作
      • 开始训练

1.halcon目标检测总工作流程:

数据集制作

* 
* 深度学习目标检测工作流程:
* 
* This example demonstrates the overall workflow for
* object detection based on deep learning, using axis-aligned bounding boxes.
* (instance_type = 'rectangle1')
* 
* PLEASE NOTE:
* - 这是一个简单的例子。
* - 为此,尽可能使用默认参数。
*   因此,结果可能与其他示例中的结果有所不同。
* - 有关更多详细步骤,请参阅该系列中的各个示例,
*   例如. detect_pills_deep_learning_1_prepare.hdev etc.
* 
dev_close_window ()
dev_update_off ()
set_system ('seed_rand', 42)
* 
* ***   0) 设置输入/输出路径   ***
* 
get_system ('example_dir', HalconExampleDir)
PillBagJsonFile := HalconExampleDir + '/hdevelop/Deep-Learning/Detection/pill_bag.json'
InputImageDir := HalconExampleDir + '/images/'
* 
OutputDir := 'detect_pills_data'
* 
* ***   1.) 准备   ***
* 
* 读入数据集
* 在这里,我们从COCO文件中读取数据
* 或者,您可以阅读DLDataset词典
* as created by e.g., the MVTec Deep Learning Tool using read_dict().
* halcon官网的一个深度学习工具可以生成需要用的数据集格式
read_dl_dataset_from_coco (PillBagJsonFile, InputImageDir, [], DLDataset)
* 这里读入数据集需要更改,具体参考https://blog.csdn.net/qq_38336419/article/details/106016641

* 使用适合于数据集的参数创建检测模型
*
create_dict (DLModelDetectionParam)
set_dict_tuple (DLModelDetectionParam, 'image_dimensions', [512,320,3])
set_dict_tuple (DLModelDetectionParam, 'max_level', 4)
get_dict_tuple (DLDataset, 'class_ids', ClassIDs)
set_dict_tuple (DLModelDetectionParam, 'class_ids', ClassIDs)
create_dl_model_detection ('pretrained_dl_classifier_compact.hdl', |ClassIDs|, DLModelDetectionParam, DLModelHandle)
* 
* 预处理DLDataset中的数据。

split_dl_dataset (DLDataset, 60, 20, [])
create_dict (PreprocessSettings)

* 在这里,现有的预处理数据将被覆盖.
set_dict_tuple (PreprocessSettings, 'overwrite_files', true)
create_dl_preprocess_param_from_model (DLModelHandle, 'false', 'full_domain', [], [], [], DLPreprocessParam)
preprocess_dl_dataset (DLDataset, OutputDir, DLPreprocessParam, PreprocessSettings, DLDatasetFileName)
* 
* 目视检查10个随机选择的预处理DLSamples
create_dict (WindowDict)
get_dict_tuple (DLDataset, 'samples', DatasetSamples)
for Index := 0 to 9 by 1
    SampleIndex := round(rand(1) * (|DatasetSamples| - 1))
    read_dl_samples (DLDataset, SampleIndex, DLSample)
    dev_display_dl_data (DLSample, [], DLDataset, 'bbox_ground_truth', [], WindowDict)
    stop ()
endfor
dev_display_dl_data_close_windows (WindowDict)
* 
* ***   2.) 训练   ***
* 设置训练相关模型参数.
set_dl_model_param (DLModelHandle, 'batch_size', 1)
set_dl_model_param (DLModelHandle, 'learning_rate', 0.001)
set_dl_model_param (DLModelHandle, 'runtime_init', 'immediately')
* 
* 在这里,我们进行了10个epoch的简短训练
* 为了获得更好的模型性能,请增加epoch数
* from 10 to e.g. 60.
create_dl_train_param (DLModelHandle, 10, 1, 'true', 42, [], [], TrainParam)
train_dl_model (DLDataset, DLModelHandle, TrainParam, 0, TrainResults, TrainInfos, EvaluationInfos)
* 
* 读取最佳模型,该模型由train_dl_model写入文件
read_dl_model ('model_best.hdl', DLModelHandle)
dev_disp_text ('Press F5 to continue', 'window', 'bottom', 'left', 'black', [], [])
stop ()
* 
dev_close_window ()
dev_close_window ()
* 
* ***   3.) 评估   ***
* 
create_dict (GenParamEval)
set_dict_tuple (GenParamEval, 'detailed_evaluation', true)
set_dict_tuple (GenParamEval, 'show_progress', true)
evaluate_dl_model (DLDataset, DLModelHandle, 'split', 'test', GenParamEval, EvaluationResult, EvalParams)
* 
create_dict (DisplayMode)
set_dict_tuple (DisplayMode, 'display_mode', ['pie_charts_precision','pie_charts_recall'])
dev_display_detection_detailed_evaluation (EvaluationResult, EvalParams, DisplayMode, WindowDict)
stop ()
dev_display_dl_data_close_windows (WindowDict)
* 
* ***   4.) 推断   ***
* 
* 为了演示推理步骤,我们将训练后的模型应用于一些随机选择的示例图像。
* 
list_image_files (InputImageDir + 'pill_bag', 'default', 'recursive', ImageFiles)
tuple_shuffle (ImageFiles, ImageFilesShuffled)
* 
set_dl_model_param (DLModelHandle, 'batch_size', 1)
* 
create_dict (WindowDict)
for IndexInference := 0 to 9 by 1
    read_image (Image, ImageFilesShuffled[IndexInference])
    gen_dl_samples_from_images (Image, DLSampleInference)
    preprocess_dl_samples (DLSampleInference, DLPreprocessParam)
    apply_dl_model (DLModelHandle, DLSampleInference, [], DLResult)
    * 
    dev_display_dl_data (DLSampleInference, DLResult, DLDataset, 'bbox_result', [], WindowDict)
    stop ()
endfor
dev_display_dl_data_close_windows (WindowDict)
* 
* 
clean_up_output (OutputDir)

准备工作

* 
* 此示例是一系列示例的一部分,该示例总结了DL目标检测的工作流程。 它使用MVTec药片数据集。
* 
* 
*四个部分是:
* 1.创建模型并进行数据集预处理。
* 2.训练模型。
* 3.评估训练后的模型。
* 4.推断新图像。
* 
* 此示例涵盖第1部分:“创建模型和数据集预处理”.
* 
* 它说明了如何创建DL对象检测模型(第1.1部分)以及为该模型调整数据的需求(预处理,第1.2部分)。
* 
dev_update_off ()
* 
* 在此示例中,在执行预处理步骤之前,将在图形窗口中对其进行说明。 
* 将以下参数设置为false可以跳过此可视化。
* 
ShowExampleScreens := true
* 
if (ShowExampleScreens)
    * 
    * 初始示例窗口和参数.
    dev_example_init (ShowExampleScreens, ExampleInternals)
    * 
    * 示例系列的简介文本.
    dev_display_screen_introduction_part_1 (ExampleInternals)
    stop ()
    dev_display_screen_introduction_part_2 (ExampleInternals)
    stop ()
    * 
    * 关于创建目标检测模型的简介文本.
    dev_display_screen_introduction_model (ExampleInternals)
    stop ()
    * 
    * 说明如何选择图像的宽度和高度.
    dev_display_screen_model_image_size (ExampleInternals)
    stop ()
    * 
    * 说明如何选择min_level和max_level.
    dev_display_screen_model_levels (ExampleInternals)
    stop ()
    * 
    * 说明如何选择子量表的锚点数量.
    dev_display_screen_model_anchor_num_subscales (ExampleInternals)
    stop ()
    * 
    * 说明如何选择锚点宽高比.
    dev_display_screen_model_anchor_aspect_ratios (ExampleInternals)
    stop ()
    * 
    * 预处理数据集的简介文本.
    dev_display_screen_preprocessing_introduction (ExampleInternals)
    stop ()
    * 
    * 说明目标检测数据集.
    dev_display_screen_detection_data_part_1 (ExampleInternals)
    stop ()
    dev_display_screen_detection_data_part_2 (ExampleInternals)
    stop ()
    * 
    * 说明拆分数据集.
    dev_display_screen_split_dataset (ExampleInternals)
    stop ()
    * 
    * 说明如何预处理数据集.
    dev_display_screen_preprocessing_data (ExampleInternals)
    stop ()
    * 
    * Run the program.
    dev_display_screen_run_program (ExampleInternals)
    stop ()
endif
* 
* *****************************************************
* *****************************************************
* **   Part 1.1: 创建目标检测模型   ***
* *****************************************************
* *****************************************************
* 
* ************************
* **   设定参数  ***
* ************************
* 
* 设置必填参数.
Backbone := 'pretrained_dl_classifier_compact.hdl'
NumClasses := 10
* 
* 网络的图像尺寸.以后,这些值将用于在预处理期间重新缩放图像
* 
ImageWidth := 512
ImageHeight := 320
ImageNumChannels := 3
* 
* 设置min_level,max_level,anchor_num_subscales和anchor_aspect_ratios.
MinLevel := 2
MaxLevel := 4
AnchorNumSubscales := 3
AnchorAspectRatios := [1.0,0.5,2.0]
* 
* 将容量设置为“中”,足以完成此任务,并提供更好的推理和训练速度
* 与“high”相比,“medium”模型的速度快两倍以上,同时显示出几乎相同的检测性能。
* 

Capacity := 'medium'
* 
* *******************************************
* **   创建目标检测模型  ***
* *******************************************
* 
* 创建通用参数名称并创建对象检测模型.
create_dict (DLModelDetectionParam)
set_dict_tuple (DLModelDetectionParam, 'image_width', ImageWidth)
set_dict_tuple (DLModelDetectionParam, 'image_height', ImageHeight)
set_dict_tuple (DLModelDetectionParam, 'image_num_channels', ImageNumChannels)
set_dict_tuple (DLModelDetectionParam, 'min_level', MinLevel)
set_dict_tuple (DLModelDetectionParam, 'max_level', MaxLevel)
set_dict_tuple (DLModelDetectionParam, 'anchor_num_subscales', AnchorNumSubscales)
set_dict_tuple (DLModelDetectionParam, 'anchor_aspect_ratios', AnchorAspectRatios)
set_dict_tuple (DLModelDetectionParam, 'capacity', Capacity)
* 
* 创建模型.
create_dl_model_detection (Backbone, NumClasses, DLModelDetectionParam, DLModelHandle)
* 
* 
* ****************************************
* ****************************************
* **   Part 1.2: 预处理数据   ***
* ****************************************
* ****************************************
* 
* ************************************
* **   设置输入和输出路径  ***
* ************************************
* 
* 所有示例数据均写入此文件夹.
ExampleDataDir := 'detect_pills_data'
* 
get_system ('example_dir', HalconExampleDir)
* 图像目录的路径.
HalconImageDir := HalconExampleDir + '/images/'
* 数据集的Json文件的路径.
PillBagJsonFile := HalconExampleDir + '/hdevelop/Deep-Learning/Detection/pill_bag.json'
* 
* 编写初始化的DL目标检测模型以在示例第2部分中进行训练.
DLModelFileName := ExampleDataDir + '/pretrained_dl_model_detection.hdl'
* 数据集目录,用于由preprocess_dl_dataset编写的任何输出.
DataDirectory := ExampleDataDir + '/dldataset_pill_bag_' + ImageWidth + 'x' + ImageHeight
* 单独存储预处理参数以使用它,例如 在推理中.
PreprocessParamFileName := DataDirectory + '/dl_preprocess_param_' + ImageWidth + 'x' + ImageHeight + '.hdict'
* 
* ************************
* **   设定参数  ***
* ************************
* 
* 分割数据集的百分比.
TrainingPercent := 70
ValidationPercent := 15
* 
* 为了获得可复制的分割,我们设置了一个随机种子.
* 这意味着重新运行脚本会导致DLDataset的拆分.
SeedRand := 42
* 
* ***************************************************
* **   读取标记的数据集并调整模型   ***
* ***************************************************
* 
* 创建输出目录(如果尚不存在).
file_exists (ExampleDataDir, FileExists)
if (not FileExists)
    make_dir (ExampleDataDir)
endif
* 
* 读入数据集.
* 在这里,我们从COCO文件中读取数据.
* 或者,您可以阅读DLDataset词典
* as created by e.g., the MVTec Deep Learning Tool using read_dict().
read_dl_dataset_from_coco (PillBagJsonFile, HalconImageDir, [], DLDataset)
* 
* 从模型中的数据集中设置类ID.
get_dict_tuple (DLDataset, 'class_ids', ClassIDs)
set_dl_model_param (DLModelHandle, 'class_ids', ClassIDs)
* 
* 编写初始化的DL目标检测模型以在第二部分中进行训练
* 
write_dl_model (DLModelHandle, DLModelFileName)

* ***********************************************************
* **   将数据集拆分为训练/验证和测试集   ***
* ***********************************************************
* 
* 为了获得可重复的结果,我们在这里设置了一个种子.
set_system ('seed_rand', SeedRand)
* 
* 产生分割.
split_dl_dataset (DLDataset, TrainingPercent, ValidationPercent, [])

* *********************************
* **   预处理数据集  ***
* *********************************
* 
* 从模型获取预处理参数.
create_dl_preprocess_param_from_model (DLModelHandle, 'false', 'full_domain', [], [], [], DLPreprocessParam)
* 
* 预处理数据集。 这可能需要几分钟.
create_dict (GenParam)
set_dict_tuple (GenParam, 'overwrite_files', true)
preprocess_dl_dataset (DLDataset, DataDirectory, DLPreprocessParam, GenParam, DLDatasetFilename)
* 
* 编写预处理参数以在以后的部分中使用它们.
write_dict (DLPreprocessParam, PreprocessParamFileName, [], [])

* *******************************************
* **   预览预处理的数据集   ***
* *******************************************
* 
* 在进行训练之前,建议先检查预处理后的数据集.
* 
* 显示10个随机选择的训练图像的DL样本.
get_dict_tuple (DLDataset, 'samples', DatasetSamples)
find_dl_samples (DatasetSamples, 'split', 'train', 'match', SampleIndices)
tuple_shuffle (SampleIndices, ShuffledIndices)
read_dl_samples (DLDataset, ShuffledIndices[0:9], DLSampleBatchDisplay)
* 
* 设置dev_display_dl_data的参数.
create_dict (WindowHandleDict)
create_dict (GenParam)
set_dict_tuple (GenParam, 'scale_windows', 1.2)
* 
* 在DLSampleBatchDisplay中显示样本.
for Index := 0 to |DLSampleBatchDisplay| - 1 by 1
    * 
    * 在DLSampleBatchDisplay中循环采样.
    dev_display_dl_data (DLSampleBatchDisplay[Index], [], DLDataset, 'bbox_ground_truth', GenParam, WindowHandleDict)
    get_dict_tuple (WindowHandleDict, 'bbox_ground_truth', WindowHandles)
    * 
    * 添加说明文字.
    dev_set_window (WindowHandles[0])
    get_dict_object (Image, DLSampleBatchDisplay[Index], 'image')
    get_image_size (Image, ImageWidth, ImageHeight)
    dev_disp_text ('New image size after preprocessing: ' + ImageWidth + ' x ' + ImageHeight, 'window', 'bottom', 'right', 'black', [], [])
    * 
    dev_set_window (WindowHandles[1])
    dev_disp_text ('Press Run (F5) to continue', 'window', 'bottom', 'right', 'black', [], [])
    stop ()
endfor
* 
* 关闭用于可视化的窗口.
dev_display_dl_data_close_windows (WindowHandleDict)
* 
if (ShowExampleScreens)
    * 提示DL检测训练过程示例.
    dev_disp_end_of_program (ExampleInternals)
    stop ()
    * Close example windows.
    dev_close_example_windows (ExampleInternals)
endif

开始训练

* 
* 本示例是一系列示例的一部分,该示例总结了DL对象检测的工作流程。 它使用MVTec药袋数据集。
* 
* 
* The four parts are:
* 1. Creation of the model and dataset preprocessing.
* 2. Training of the model.
* 3. Evaluation of the trained model.
* 4. Inference on new images.
* 
* 此示例包含第2部分:“模型训练”.
* 
* 它说明了如何在预处理的数据集上训练对象检测模型。 请注意:此脚本需要第1部分的输出detect_pills_deep_learning_1_preparation.hdev

* 
dev_update_off ()
* 
* 在此示例中,训练步骤在执行之前在图形窗口中进行了说明。 将以下参数设置为false可以跳过此可视化.

ShowExampleScreens := true
* 
* 显示有关此示例的说明性屏幕.
if (ShowExampleScreens)
    * 
    * 初始示例窗口和参数等.
    dev_example_init (ShowExampleScreens, ExampleInternals)
    * 
    * 示例系列的介绍文字.
    dev_display_screen_introduction_train (ExampleInternals)
    stop ()
    * 
    * Check for requirements.
    dev_display_screen_error (ExampleInternals, Error)
    if (Error)
        stop ()
    endif
    * 
    * 在训练中说明目标.
    dev_display_screen_training_goals_1 (ExampleInternals)
    stop ()
    dev_display_screen_training_goals_2 (ExampleInternals)
    stop ()
    * 
    * 解释set_dl_model_param和create_dl_train_param.
    dev_display_screen_parameters (ExampleInternals)
    stop ()
    * 
    * 说明batch_size.
    dev_display_screen_batch_size (ExampleInternals)
    stop ()
    * 
    * 说明学习率.
    dev_display_screen_learning_rate (ExampleInternals)
    stop ()
    * 
    * 解释epoch数.
    dev_display_screen_num_epochs (ExampleInternals)
    stop ()
    * 
    * 说明其他参数.
    dev_display_screen_other_params (ExampleInternals)
    stop ()
    * 
    * Explain train_dl_model.
    dev_display_screen_training_process (ExampleInternals)
    stop ()
    * 
    * 说明训练将从现在开始.
    dev_display_screen_training_starts (ExampleInternals)
    stop ()
    * 
    * Close any example screen windows.
    dev_close_example_windows (ExampleInternals)
endif
* 
* *****************************************************
* ***          设置输入输出路径.          ***
* *****************************************************
* 
* 所有示例数据均写入此文件夹.
ExampleDataDir := 'detect_pills_data'
* 初始化模型的文件路径.
InitialModelFileName := ExampleDataDir + '/pretrained_dl_model_detection.hdl'
* 预处理的DLDataset的文件路径.
DataDirectory := ExampleDataDir + '/dldataset_pill_bag_512x320'
DLDatasetFileName := DataDirectory + '/dl_dataset.hdict'
* 
* 最佳评估模型的输出路径.
BestModelBaseName := ExampleDataDir + '/best_dl_model_detection'
* 最终训练模型的输出路径.
FinalModelBaseName := ExampleDataDir + '/final_dl_model_detection'
* 
* *****************************************************
* ***             设置基本参数.             ***
* *****************************************************
* 以下参数需要经常修改.
* 
* 模型参数.
* Batch size.
BatchSize := 2
* 初始学习率.
InitialLearningRate := 0.0005
* 如果批量小,动量应该高.
Momentum := 0.99
* 
* train_dl_model使用的参数.
* 训练模型的epochs数.
NumEpochs := 60
* 评估间隔(以epoch计),以计算验证拆分中的评估度量.
EvaluationIntervalEpochs := 1
* 在以下世代更改学习率,例如 [15,30].
* 如果不应更改学习率,请将其设置为[].
ChangeLearningRateEpochs := 30
* 将学习率更改为以下值,例如 InitialLearningRate * [0.1,0.01].
* 元组的长度必须与ChangeLearningRateEpochs相同.
ChangeLearningRateValues := InitialLearningRate * 0.1
* 
* *****************************************************
* ***          设置超参数.            ***
* *****************************************************
* 在极少数情况下,可能需要更改以下参数.
* 
* Model parameter.
* 事先设置权重.
WeightPrior := 0.00001
* 
* Parameters used by train_dl_model.
* 控制是否显示训练进度(是/否).
DisplayEvaluation := true
* Set a random seed for training.
SeedRandom := 42
* 
* 设置create_dl_train_param的通用参数.
* 请参阅create_dl_train_param的文档以获取所有可用参数的概述.
GenParamName := []
GenParamValue := []
* 
* 扩充参数.
* 如果在训练期间应增加样本,请创建expand_dl_samples所需的字典.
* 在这里,我们设置增强百分比和方法.
create_dict (AugmentationParam)
* 增加的样本百分比.
set_dict_tuple (AugmentationParam, 'augmentation_percentage', 50)
* 沿行和列镜像.
set_dict_tuple (AugmentationParam, 'mirror', 'rc')
GenParamName := [GenParamName,'augment']
GenParamValue := [GenParamValue,AugmentationParam]
* 
* Change strategies.
* 训练期间可以更改模型参数.
* 在这里,如果上面指定了,我们将更改学习率.
if (|ChangeLearningRateEpochs| > 0)
    create_dict (ChangeStrategy)
    * 指定要更改的模型参数,此处为学习率.
    set_dict_tuple (ChangeStrategy, 'model_param', 'learning_rate')
    * 在“ initial_value”处启动参数值.
    set_dict_tuple (ChangeStrategy, 'initial_value', InitialLearningRate)
    * 在以下epoch降低学习率.
    set_dict_tuple (ChangeStrategy, 'epochs', ChangeLearningRateEpochs)
    * Reduce the learning rate to the following value at epoch 30.
    set_dict_tuple (ChangeStrategy, 'values', ChangeLearningRateValues)
    * Collect all change strategies as input.
    GenParamName := [GenParamName,'change']
    GenParamValue := [GenParamValue,ChangeStrategy]
endif
* 
* 序列化策略.
* 有几种将中间模型保存到磁盘的选项(请参见create_dl_train_param).
* 在这里,最佳和最终模型将保存到上面设置的路径.
create_dict (SerializationStrategy)
set_dict_tuple (SerializationStrategy, 'type', 'best')
set_dict_tuple (SerializationStrategy, 'basename', BestModelBaseName)
GenParamName := [GenParamName,'serialize']
GenParamValue := [GenParamValue,SerializationStrategy]
create_dict (SerializationStrategy)
set_dict_tuple (SerializationStrategy, 'type', 'final')
set_dict_tuple (SerializationStrategy, 'basename', FinalModelBaseName)
GenParamName := [GenParamName,'serialize']
GenParamValue := [GenParamValue,SerializationStrategy]
* 
* *****************************************************
* ***       读取初始模型和数据集.         ***
* *****************************************************
* 
* 检查是否所有必需的文件都存在.
check_files_availability (ExampleDataDir, InitialModelFileName, DLDatasetFileName)
* 
* 读入在预处理过程中初始化的模型.
read_dl_model (InitialModelFileName, DLModelHandle)
* 
* 读入预处理的DLDataset文件.
read_dict (DLDatasetFileName, [], [], DLDataset)
* 
* *****************************************************
* ***             设置模型参数.             ***
* *****************************************************
* 
* 根据上面的设置来设置模型超参数.
set_dl_model_param (DLModelHandle, 'learning_rate', InitialLearningRate)
set_dl_model_param (DLModelHandle, 'momentum', Momentum)
set_dl_model_param (DLModelHandle, 'batch_size', BatchSize)
if (|WeightPrior| > 0)
    set_dl_model_param (DLModelHandle, 'weight_prior', WeightPrior)
endif
set_dl_model_param (DLModelHandle, 'runtime_init', 'immediately')
* 
* *****************************************************
* ***               训练模型.                ***
* *****************************************************
* 
* 创建训练参数.
create_dl_train_param (DLModelHandle, NumEpochs, EvaluationIntervalEpochs, DisplayEvaluation, SeedRandom, GenParamName, GenParamValue, TrainParam)
* 
* 开始训练.
train_dl_model (DLDataset, DLModelHandle, TrainParam, 0.0, TrainResults, TrainInfos, EvaluationInfos)
* 
* 训练结束后停止,然后关闭窗户.
dev_disp_text ('Press Run (F5) to continue', 'window', 'bottom', 'right', 'black', [], [])
stop ()
* 
* 关闭训练窗口.
dev_close_window ()
dev_close_window ()
* 
* 显示最后的示例屏幕.
if (ShowExampleScreens)
    * 提示DL检测评估和推断示例.
    dev_display_screen_final (ExampleInternals)
    stop ()
    * Close example windows.
    dev_close_example_windows (ExampleInternals)
endif

你可能感兴趣的:(机器视觉,深度学习,人工智能)