当前位置:   article > 正文

halcon 深度学习(一):分类_hdict深度学习

hdict深度学习

分类识别系统下载地址:https://download.csdn.net/download/jbossjf/78056467

  1. *准备训练集
  2. dev_update_off ()
  3. *存放分类图片的上一级路径
  4. RawImageFolder := 'D:/软件项目备份/halcon项目/深度学习分类/分类检测/'
  5. *存放预处理数据的总路径
  6. ExampleDataDir:= 'D:/软件项目备份/halcon项目/深度学习分类/分类检测/class_data'
  7. *存放预处理数据的二级路径
  8. DataDirectoryBaseName := ExampleDataDir + '/dldataset_pokeman'
  9. *默认参数,用来预处理数据集的
  10. LabelSource := 'last_folder'
  11. *
  12. *分割数据集的百分比。
  13. *训练集
  14. TrainingPercent := 70
  15. *验证集
  16. ValidationPercent := 15
  17. *
  18. * 用户想要输入的图像大小,可更改
  19. ImageWidth := 900
  20. ImageHeight := 500
  21. ImageNumChannels := 3
  22. *
  23. *用于图像预处理的其他参数。
  24. NormalizationType := 'none'
  25. DomainHandling := 'full_domain'
  26. *
  27. *为了获得可复制的分割,我们设置了一个随机种子。
  28. *这意味着重新运行脚本将导致DLDataset的相同拆分。
  29. SeedRand := 42
  30. *设置随机种子。
  31. set_system ('seed_rand', SeedRand)
  32. *
  33. *使用过程read_dl_dataset_classification读取数据集。
  34. *或者,您可以使用read_dict()读取由MVTec深度学习工具创建的DLDataset字典。
  35. read_dl_dataset_classification (RawImageFolder, LabelSource, DLDataset)
  36. *分割数据集
  37. split_dl_dataset (DLDataset, TrainingPercent, ValidationPercent, [])
  38. *创建输出目录(如果尚不存在)。
  39. file_exists (ExampleDataDir, FileExists)
  40. if (not FileExists)
  41. make_dir (ExampleDataDir)
  42. endif
  43. *
  44. *创建预处理参数。
  45. create_dl_preprocess_param ('classification', ImageWidth, ImageHeight, ImageNumChannels, -127, 128, NormalizationType, DomainHandling, [], [], [], [], DLPreprocessParam)
  46. *
  47. *数据集目录,用于由preprocess_dl_dataset编写的任何输出。
  48. DataDirectory := DataDirectoryBaseName + '_' + ImageWidth + 'x' + ImageHeight
  49. *
  50. *预处理数据集。 这可能需要几秒钟。
  51. create_dict (GenParam)
  52. set_dict_tuple (GenParam, 'overwrite_files', true)
  53. preprocess_dl_dataset (DLDataset, DataDirectory, DLPreprocessParam, GenParam, DLDatasetFileName)
  54. *
  55. *单独存储预处理参数以便使用,例如 在推论过程中。
  56. PreprocessParamFileBaseName := DataDirectory + '/dl_preprocess_param.hdict'
  57. write_dict (DLPreprocessParam, PreprocessParamFileBaseName, [], [])
  58. *打标签
  59. *在进行培训之前,建议先检查预处理后的数据集。
  60. *
  61. *显示10个随机选择的火车图像的DLSamples。
  62. get_dict_tuple (DLDataset, 'samples', DatasetSamples)
  63. find_dl_samples (DatasetSamples, 'split', 'train', 'match', SampleIndices)
  64. tuple_shuffle (SampleIndices, ShuffledIndices)
  65. read_dl_samples (DLDataset, ShuffledIndices[0:9], DLSampleBatchDisplay)
  66. *
  67. create_dict (WindowHandleDict)
  68. for Index := 0 to |DLSampleBatchDisplay| - 1 by 1
  69. *在DLSampleBatchDisplay中循环采样。
  70. dev_display_dl_data (DLSampleBatchDisplay[Index], [], DLDataset, 'classification_ground_truth', [], WindowHandleDict)
  71. Text := 'Press Run (F5) to continue'
  72. dev_disp_text (Text, 'window', 'bottom', 'right', 'black', [], [])
  73. stop ()
  74. endfor
  75. *
  76. * 关闭窗口,数据预处理完成
  77. dev_close_window_dict (WindowHandleDict)
  78. stop()
  79. *训练模型
  80. *预处理后的文件路径
  81. DLDatasetFileName := DataDirectory+'/dl_dataset.hdict'
  82. *预处理的参数文件路径
  83. DLPreprocessParamFileName := DataDirectory + '/dl_preprocess_param.hdict'
  84. *最佳评估模型的输出路径。
  85. BestModelBaseName := ExampleDataDir + '/best_dl_model_classification'
  86. *最终训练模型的输出路径。
  87. FinalModelBaseName := ExampleDataDir + '/final_dl_model_classification'
  88. * Batch size.
  89. BatchSize := 2
  90. *学习率
  91. InitialLearningRate := 0.0001
  92. *如果批量小,动量应高。
  93. Momentum := 0.9
  94. * train_dl_model使用的参数。
  95. *训练模型的时迭代次数。
  96. NumEpochs := 20
  97. *评估间隔(以时期计),以计算验证拆分上的评估度量。每迭代一次验证一次
  98. EvaluationIntervalEpochs := 1
  99. *在以下时期更改学习率,例如 [4812]。
  100. *如果不应该改变学习率,则将其设置为[]。
  101. ChangeLearningRateEpochs := []
  102. *将学习率更改为以下值,例如 InitialLearningRate * [0.10.010.001]。
  103. *元组的长度必须与ChangeLearningRateEpochs相同。
  104. ChangeLearningRateValues := InitialLearningRate * [0.1,0.01,0.001]
  105. *事先设定权重。
  106. WeightPrior := 0.0005
  107. *控制是否显示训练进度(是/否)。
  108. DisplayEvaluation := true
  109. *设置一个随机的种子进行训练。
  110. RandomSeed := 42
  111. *设置create_dl_train_param的通用参数。
  112. *请参阅create_dl_train_param的文档以获取所有可用参数的概述。
  113. GenParamName := []
  114. GenParamValue := []
  115. *扩充参数。
  116. *如果在训练过程中应增加样本,请创建extend_dl_samples所需的字典。
  117. *在这里,我们设置增强百分比和方法。
  118. *create_dict (AugmentationParam)
  119. *要增加的样本百分比。
  120. *set_dict_tuple (AugmentationParam, 'augmentation_percentage', 50)
  121. *沿行和列镜像。
  122. *set_dict_tuple (AugmentationParam, 'mirror', 'rc')
  123. *GenParamName := [GenParamName,'augment']
  124. *GenParamValue := [GenParamValue,AugmentationParam]
  125. *更改策略。
  126. *在训练过程中可以更改模型参数。
  127. *在这里,如果上面指定了,我们将更改学习率。
  128. if (|ChangeLearningRateEpochs| > 0)
  129. create_dict (ChangeStrategy)
  130. * Specify the model parameter to be changed, here the learning rate.
  131. set_dict_tuple (ChangeStrategy, 'model_param', 'learning_rate')
  132. * Start the parameter value at 'initial_value'.
  133. set_dict_tuple (ChangeStrategy, 'initial_value', InitialLearningRate)
  134. * Reduce the learning rate in the following epochs.
  135. set_dict_tuple (ChangeStrategy, 'epochs', ChangeLearningRateEpochs)
  136. * Reduce the learning rate to the following values.
  137. set_dict_tuple (ChangeStrategy, 'values', ChangeLearningRateValues)
  138. * Collect all change strategies as input.
  139. GenParamName := [GenParamName,'change']
  140. GenParamValue := [GenParamValue,ChangeStrategy]
  141. endif
  142. *
  143. *序列化策略。
  144. *有多种选项可用于将中间模型保存到磁盘(请参见create_dl_train_param)。
  145. *在这里,我们将最佳模型和最终模型保存到上面设置的路径中。
  146. create_dict (SerializationStrategy)
  147. set_dict_tuple (SerializationStrategy, 'type', 'best')
  148. set_dict_tuple (SerializationStrategy, 'basename', BestModelBaseName)
  149. GenParamName := [GenParamName,'serialize']
  150. GenParamValue := [GenParamValue,SerializationStrategy]
  151. create_dict (SerializationStrategy)
  152. set_dict_tuple (SerializationStrategy, 'type', 'final')
  153. set_dict_tuple (SerializationStrategy, 'basename', FinalModelBaseName)
  154. GenParamName := [GenParamName,'serialize']
  155. GenParamValue := [GenParamValue,SerializationStrategy]
  156. *
  157. *显示参数。
  158. *在此示例中,选择了20%的训练分组以显示
  159. *评估在训练过程中减少训练次数的评估措施。 较低的百分比
  160. *有助于加快评估/培训。 如果评估措施用于培训分裂
  161. *不会显示,将此值设置为0(默认值)。
  162. *SelectedPercentageTrainSamples := 15
  163. *create_dict (DisplayParam)
  164. *set_dict_tuple (DisplayParam, 'selected_percentage_train_samples', SelectedPercentageTrainSamples)
  165. *GenParamName := [GenParamName,'display']
  166. *GenParamValue := [GenParamValue,DisplayParam]
  167. *检查是否所有必需的文件都存在。
  168. *check_data_availability (ExampleDataDir, DLDatasetFileName, DLPreprocessParamFileName)
  169. *
  170. *读入在预处理过程中初始化的模型。也就是读取神经网络模型,halcon自带的
  171. read_dl_model ('pretrained_dl_classifier_compact.hdl', DLModelHandle)
  172. *读取预处理后的图片DLDataset文件。
  173. read_dict (DLDatasetFileName, [], [], DLDataset)
  174. *按照上述设置指定模型超参数。
  175. set_dl_model_param (DLModelHandle, 'learning_rate', InitialLearningRate)
  176. set_dl_model_param (DLModelHandle, 'momentum', Momentum)
  177. *设置模型的类名。
  178. get_dict_tuple (DLDataset, 'class_names', ClassNames)
  179. set_dl_model_param (DLModelHandle, 'class_names', ClassNames)
  180. *从预处理参数获取图像尺寸并为模型设置它们。
  181. read_dict (DLPreprocessParamFileName, [], [], DLPreprocessParam)
  182. get_dict_tuple (DLPreprocessParam, 'image_width', ImageWidth)
  183. get_dict_tuple (DLPreprocessParam, 'image_height', ImageHeight)
  184. get_dict_tuple (DLPreprocessParam, 'image_num_channels', ImageNumChannels)
  185. *设置输入模型的图片大小和维度
  186. set_dl_model_param (DLModelHandle, 'image_dimensions', [ImageWidth,ImageHeight,ImageNumChannels])
  187. if (BatchSize == 'maximum')
  188. set_dl_model_param_max_gpu_batch_size (DLModelHandle, 100)
  189. else
  190. set_dl_model_param (DLModelHandle, 'batch_size', BatchSize)
  191. endif
  192. if (|WeightPrior| > 0)
  193. set_dl_model_param (DLModelHandle, 'weight_prior', WeightPrior)
  194. endif
  195. set_dl_model_param (DLModelHandle, 'runtime_init', 'immediately')
  196. stop()
  197. *创建训练参数。有超参数的传入GenParamName、GenParamValue
  198. create_dl_train_param (DLModelHandle, NumEpochs, EvaluationIntervalEpochs, DisplayEvaluation, RandomSeed, GenParamName, GenParamValue, TrainParam)
  199. *create_dl_train_param (DLModelHandle, NumEpochs, EvaluationIntervalEpochs, DisplayEvaluation, RandomSeed, [], [], TrainParam)
  200. *
  201. *以下过程中的train_dl_model_batch()。
  202. train_dl_model (DLDataset, DLModelHandle, TrainParam, 0, TrainResults, TrainInfos, EvaluationInfos)
  203. stop()
  204. * Close training windows.
  205. dev_close_window ()
  206. *评估模型
  207. *******************************************************************评估****************************************************
  208. *创建字典
  209. create_dict (GenParamEval)
  210. *设置参数
  211. set_dict_tuple (GenParamEval, 'class_names_to_evaluate', 'global')
  212. set_dict_tuple (GenParamEval, 'measures', ['top1_error','precision','recall','f_score','absolute_confusion_matrix'])
  213. * Evaluate the trained model.
  214. evaluate_dl_model (DLDataset, DLModelHandle, 'split', 'test', GenParamEval, EvaluationResult, EvalParams)
  215. *
  216. create_dict (EvalDisplayMode)
  217. set_dict_tuple (EvalDisplayMode, 'display_mode', ['measures','pie_charts_precision','pie_charts_recall','absolute_confusion_matrix'])
  218. create_dict (WindowDict)
  219. dev_display_classification_evaluation (EvaluationResult, EvalParams, EvalDisplayMode, WindowDict)
  220. dev_disp_text ('Press F5 to continue', 'window', 'bottom', 'right', 'black', [], [])
  221. stop ()
  222. dev_close_window_dict (WindowDict)
  223. BestModelBaseName := 'D:/软件项目备份/halcon项目/深度学习分类/分类检测/class_data/best_dl_model_classification.hdl'
  224. *读取保存好的最佳模型
  225. read_dl_model (BestModelBaseName, DLModelHandle)
  226. *读取预处理的参数
  227. read_dict ('D:/软件项目备份/halcon项目/深度学习分类/分类检测/class_data/dldataset_pokeman_900x500/dl_preprocess_param.hdict', [], [], DLPreprocessParam)
  228. get_dict_tuple (DLPreprocessParam, 'image_width', ImageWidth)
  229. get_dict_tuple (DLPreprocessParam, 'image_height', ImageHeight)
  230. get_dict_tuple (DLPreprocessParam, 'image_num_channels', ImageNumChannels)
  231. *create_dict (WindowDict)
  232. dev_open_window (0, 0, 900, 512, 'black', WindowHandle)
  233. * Image Acquisition 01: Code generated by Image Acquisition 01
  234. list_files ('D:/软件项目备份/halcon项目/深度学习分类/分类检测/苹果', ['files','follow_links'], ImageFiles)
  235. tuple_regexp_select (ImageFiles, ['\\.(tif|tiff|gif|bmp|jpg|jpeg|jp2|png|pcx|pgm|ppm|pbm|xwd|ima|hobj)$','ignore_case'], ImageFiles)
  236. for Index := 0 to |ImageFiles| - 1 by 1
  237. read_image (Image, ImageFiles[Index])
  238. dev_display (Image)
  239. * 处理图片
  240. gen_dl_samples_from_images (Image, DLSample)
  241. preprocess_dl_samples (DLSample, DLPreprocessParam)
  242. *喂给模型
  243. apply_dl_model (DLModelHandle, DLSample, [], DLResult)
  244. *得到预判结果
  245. get_dict_tuple (DLResult, 'classification_class_names', Tuple)
  246. predictionname:=Tuple[0]
  247. *显示预测的类型
  248. disp_message (WindowHandle, predictionname, 'window', 12, 12, 'black', 'true')
  249. *dev_display_dl_data (DLSample, DLResult, DLDataset, 'classification_result', [], WindowDict)
  250. stop()
  251. endfor

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/883779
推荐阅读
相关标签
  

闽ICP备14008679号