Halcon 深度学习语义分割

news/2024/11/20 15:33:56/

1.1根据txt格式标签生成Label图片

(1) 经过测试验证,使用python代码或者halcon代码生成的Label图片是一样的。但要注意,最后要生成png格式的Label图片。

(2) 使用python代码生成Label图片

import cv2
import os
import numpy as npdef gen_label_img(img_path, txt_label_path, png_label_path):img_file_name = os.path.basename(img_path).split('.jpg')[0]print(img_file_name)img = cv2.imread(img_path)h, w = img.shape[:2]mask = np.zeros((h, w), dtype=np.uint8)with open(txt_label_path, 'r') as f:for line in f.readlines():class_id, *pyly = line.strip().split(' ')pyly = [float(i) for i in pyly]pyly = np.array(pyly).reshape(-1, 2)# 根据h,w进行反归一化pyly = (pyly * np.array([w, h])).astype(np.int32)print()mask = cv2.drawContours(mask, [pyly], -1, (int(class_id) + 255, int(class_id) + 255, int(class_id) + 255), -1)cv2.imwrite(png_label_path + '/' + img_file_name+'.png', mask)if __name__ == "__main__":img_path1 = r'./DataImage/train/'txt_label_path1 = r'./DataLabel/txtlabel/train/'png_label_path = r'./DataLabel/pnglabel/train2'print(os.listdir(img_path1))for img_file in os.listdir(img_path1):img_path2 = img_path1 + img_fileprint(img_path2)txt_label_path2 = txt_label_path1 + img_file.split('.')[0] + '.txt'gen_label_img(img_path2, txt_label_path2, png_label_path)

(3) 使用halcon代码生成Label图片

img_path:='./DataImage/train'
txt_path:='./DataLabel/txtlabel/train'
label_path:='./DataLabel/pnglabel/train1'
list_image_files (img_path, 'default', [], ImageFiles)for i:= 0 to |ImageFiles|-1 by 1read_image (Image1, ImageFiles[i])get_image_size (Image1, Width, Height)gen_image_const(ImageResult,'byte',Width,Height)     parse_filename (ImageFiles[i], BaseName, Extension, Directory)txt_file_path:= txt_path+'/'+BaseName+'.txt'label_file_path:=label_path+'/'+BaseNameopen_file (txt_file_path, 'input', FileHandle)repeatfread_line(FileHandle, oneline, IsEOF)if(IsEOF == 1)break        endifif(oneline == ' ' or oneline=='\n')continueendiftuple_regexp_replace (oneline, '\n', '', oneline)tuple_split (oneline, ' ', Substrings)tuple_number (Substrings, Number)Points:=Number[1:|Number|-1] tuple_select (Points, [0:2:|Points|-1], Selected1)tuple_select (Points, [1:2:|Points|], Selected2)c:= Selected1*Widthr:= Selected2*Heightgen_region_polygon_filled (Region, r, c)paint_region (Region, ImageResult, ImageResult, 255, 'fill')until (IsEOF)write_image (ImageResult, 'png', 0,label_file_path)endfor

1.2应用示例代码

* 
* ***   0) SET INPUT/OUTPUT PATHS AND DATASET PARAMETERS   ***
* 
ImageDir := 'pill'
SegmentationDir := 'labels/pill'
* 
OutputDir := 'segment_pill_defects_data'
* 
ClassNames := ['good', 'contamination', 'crack']
ClassIDs := [0, 1, 2]
* Set to true, if the results should be deleted after running this program.
RemoveResults := false
* 
* ***   1.) PREPARE   ***
* 
* Read and prepare the DLDataset.
read_dl_dataset_segmentation (ImageDir, SegmentationDir, ClassNames, ClassIDs, [], [], [], DLDataset)
split_dl_dataset (DLDataset, 60, 20, [])
* Here, existing preprocessed data will be overwritten if necessary.
PreprocessSettings := dict{overwrite_files: 'auto'}
create_dl_preprocess_param ('segmentation', 400, 400, 3, -127, 128, 'none', 'full_domain', [], [], [], [], DLPreprocessParam)
preprocess_dl_dataset (DLDataset, OutputDir, DLPreprocessParam, PreprocessSettings, DLDatasetFileName)
* 
* Inspect 10 randomly selected preprocessed DLSamples visually.
WindowDict := dict{}
find_dl_samples (DLDataset.samples, 'split', 'train', 'match', TrainSampleIndices)
for Index := 0 to 9 by 1SampleIndex := TrainSampleIndices[round(rand(1) * (|TrainSampleIndices| - 1))]read_dl_samples (DLDataset, SampleIndex, DLSample)dev_display_dl_data (DLSample, [], DLDataset, ['segmentation_image_ground_truth', 'segmentation_weight_map'], [], WindowDict)dev_disp_text ('Press F5 to continue', 'window', 'bottom', 'right', 'black', [], [])stop ()
endfor
dev_close_window_dict (WindowDict)
* 
* ***   2.) TRAIN   ***
* 
* Read a pretrained model and adapt its parameters
* according to the dataset.
read_dl_model ('pretrained_dl_segmentation_compact.hdl', DLModelHandle)
set_dl_model_param_based_on_preprocessing (DLModelHandle, DLPreprocessParam, ClassIDs)
set_dl_model_param (DLModelHandle, 'class_names', ClassNames)
* Set training related model parameters.
* Training can be performed on a GPU or CPU.
* See the respective system requirements in the Installation Guide.
* If possible a GPU is used in this example.
* In case you explicitly wish to run this example on the CPU,
* choose the CPU device instead.
query_available_dl_devices (['runtime', 'runtime'], ['gpu', 'cpu'], DLDeviceHandles)
if (|DLDeviceHandles| == 0)throw ('No supported device found to continue this example.')
endif
* Due to the filter used in query_available_dl_devices, the first device is a GPU, if available.
DLDevice := DLDeviceHandles[0]
get_dl_device_param (DLDevice, 'type', DLDeviceType)
if (DLDeviceType == 'cpu')* The number of used threads may have an impact* on the training duration.NumThreadsTraining := 4set_system ('thread_num', NumThreadsTraining)
endif
* 
* For details see the documentation of set_dl_model_param () and get_dl_model_param ().
if (DLDeviceType == 'gpu')set_dl_model_param_max_gpu_batch_size (DLModelHandle, 50)
endif
set_dl_model_param (DLModelHandle, 'learning_rate', 0.0001)
set_dl_model_param (DLModelHandle, 'device', DLDevice)
* 
* Here, we run a short training of 10 epochs.
* For better model performance increase the number of epochs
* and train as long as your compute budget allows,
* e.g., for 100, 1000 or 3000 epochs.
create_dl_train_param (DLModelHandle, 10, 1, 'true', 42, [], [], TrainParam)
* The training and thus the call of train_dl_model_batch ()
* is done using the following procedure.
train_dl_model (DLDataset, DLModelHandle, TrainParam, 0, TrainResults, TrainInfos, EvaluationInfos)
* 
* Read the best model, which is written to file by 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.) EVALUATE   ***
* 
GenParamEval := dict{show_progress: true}
GenParamEval.measures := ['mean_iou', 'pixel_accuracy', 'class_pixel_accuracy', 'pixel_confusion_matrix']
* 
set_dl_model_param (DLModelHandle, 'device', DLDevice)
evaluate_dl_model (DLDataset, DLModelHandle, 'split', 'test', GenParamEval, EvaluationResult, EvalParams)
* 
GenParamEvalDisplay := dict{display_mode: ['measures', 'absolute_confusion_matrix']}
dev_display_segmentation_evaluation (EvaluationResult, EvalParams, GenParamEvalDisplay, WindowDict)
dev_disp_text ('Press F5 to continue', 'window', 'bottom', 'right', 'black', [], [])
stop ()
dev_close_window_dict (WindowDict)
* 
* Optimize the model for inference,
* meaning, reduce its memory consumption.
set_dl_model_param (DLModelHandle, 'optimize_for_inference', 'true')
set_dl_model_param (DLModelHandle, 'batch_size', 1)
* Save the model in this optimized state.
write_dl_model (DLModelHandle, 'model_best.hdl')
* 
* ***   4.) INFER   ***
* 
* To demonstrate the inference steps, we apply the
* trained model to some randomly chosen example images.
list_image_files (ImageDir, 'default', 'recursive', ImageFiles)
tuple_shuffle (ImageFiles, ImageFilesShuffled)
* 
* Create dictionaries used in visualization.
WindowDict := dict{}
DLDatasetInfo := dict{}
get_dl_model_param (DLModelHandle, 'class_ids', DLDatasetInfo.class_ids)
get_dl_model_param (DLModelHandle, 'class_names', DLDatasetInfo.class_names)
for IndexInference := 0 to 9 by 1read_image (Image, ImageFilesShuffled[IndexInference])gen_dl_samples_from_images (Image, DLSample)preprocess_dl_samples (DLSample, DLPreprocessParam)apply_dl_model (DLModelHandle, DLSample, [], DLResult)* dev_display_dl_data (DLSample, DLResult, DLDatasetInfo, ['segmentation_image_result', 'segmentation_confidence_map'], [], WindowDict)dev_disp_text ('Press F5 to continue', 'window', 'bottom', 'right', 'black', [], [])stop ()
endfor
dev_close_window_dict (WindowDict)
* 
* ***   5.) REMOVE FILES   ***
* 
clean_up_output (OutputDir, RemoveResults)


http://www.ppmy.cn/news/1271480.html

相关文章

Java系列-ConcurrentHashMap构造方法

1.无参 什么都没做 public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>implements ConcurrentMap<K,V>, Serializable {private static final float LOAD_FACTOR 0.75f;public ConcurrentHashMap() {} } 2.带初始容量 public class Concurr…

Go实现MapReduce

背景 当谈到处理大规模数据集时&#xff0c;MapReduce是一种备受欢迎的编程模型。它最初由Google开发&#xff0c;用于并行处理大规模数据以提取有价值的信息。MapReduce模型将大规模数据集分解成小块&#xff0c;然后对这些小块进行映射和归约操作&#xff0c;最终产生有用的…

恒创科技:有哪些免费的CDN加速服务

CDN加速技术已经成为提升网站性能和用户体验的重要手段之一。许多网站都使用CDN来加速内容传输&#xff0c;提高网站的响应速度和可用性。然而&#xff0c;对于许多小型企业和个人网站来说&#xff0c;使用CDN服务需要支付一定的费用。那么&#xff0c;有没有免费的CDN加速服务…

C#基础——语法学习

C#的基本语法 在介绍基本语法之前我们先来大概讲一下创建好的这些文件都是做什么的 .sln文件&#xff1a;将项目和解决方案项结合到一起 .vs文件夹&#xff1a;用来存储当前解决方案中关于用户的设置和自定义项&#xff0c;比如断点&#xff0c;主题等。&#xff08;一般都将其…

FreeModbus--学习函数指针

目录 函数指针 最简单的例子 稍作修改例子 引入协议栈的函数指针 引入协议栈第二处函数指针 函数指针 该协议栈中使用到函数指针&#xff0c;现开展一篇专门存放函数指针的文章。 C语言的函数指针是指向函数的指针变量&#xff0c;可以用来存储和调用函数的地址。在C语言中…

Tomcat-安装部署(源码包安装)

一、简介 Tomcat 是由 Apache 开发的一个 Servlet 容器&#xff0c;实现了对 Servlet 和 JSP 的支持&#xff0c;并提供了作为Web服务器的一些特有功能&#xff0c;如Tomcat管理和控制平台、安全域管理和Tomcat阀等。 简单来说&#xff0c;Tomcat是一个WEB应用程序的托管平台…

锁--07_1----插入意向锁-Insert加锁过程

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 插入意向锁MySQL执行插入Insert时的加锁过程MySQL官方文档MySQL insert加锁流程1.加插入意向锁2.判断插入记录是否有唯一键3. 插入记录并对记录加X锁插入意向锁----…

提升开发效率的免费API好物

日出日落&#xff1a;支持国内3400个城市以及国际4万个城市&#xff0c;获取指定城市/地点每日日出时间、日落时间&#xff1b;同时也支持全球任意经纬度查询&#xff0c;接口会返回该经纬度最近的日出日落信息。月出月落和月相&#xff1a;支持国内3400个城市以及国际4万个城市…