HALCON示例程序train_characters_ocr.hdev使用SVM分类器训练字体
小哥哥小姐姐觉得有用点个赞呗!
示例程序源码(加注释)
蓝色字体均为算子解释链接,可以前往查看解答
- 关于显示类函数解释
read_image (Image, ‘ocr/chars_training_01.png’) - 获取单通道图像的指针
get_image_pointer1 (Image, Pointer, Type, Width, Height)
dev_close_window ()
dev_open_window (0, 0, Width, Height, ‘white’, WindowHandle)
set_display_font (WindowHandle, 12, ‘mono’, ‘true’, ‘false’)
dev_set_draw (‘margin’)
dev_set_line_width (2)
dev_display (Image)
dev_update_window (‘off’)
dev_update_pc (‘off’)
dev_update_var (‘off’) - 创建一个 SVM 分类器内容,从A-G
ClassNames := [‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’] - 创建OCR分类器
create_ocr_class_svm (8, 10, ‘constant’, [‘convexity’,‘num_holes’,‘projection_horizontal’,‘projection_vertical’], ClassNames, ‘rbf’, 0.02, 0.05, ‘one-versus-one’, ‘normalization’, 10, OCRHandle)
for i := 1 to 7 by 1
read_image (Image, ‘ocr/chars_training_’ + i$’.2d’)
dev_display (Image)
* halcon自定义函数大括号内为其代码
get_regions (Image, SortedRegions)
{
dev_set_color (‘white’)
- 二值化
threshold (Image, Region, 0, 125) - 分割连通域
connection (Region, ConnectedRegions) - 通过面积筛选区域
select_shape (ConnectedRegions, SelectedRegions, ‘area’, ‘and’, 50, 999999) - 对区域进行排序
sort_region (SelectedRegions, SortedRegions, ‘character’, ‘true’, ‘row’)
return ()
}- 对元素进行计数
count_obj (SortedRegions, NumberObjects)
for j := 1 to NumberObjects by 1 - 选取数组内指定元素
select_obj (SortedRegions, ObjectSelected, j)
if (i == 1 and j == 1)- 将训练字符储存到指定文件
write_ocr_trainf (ObjectSelected, Image, ClassNames[j - 1], ‘train_characters_ocr.trf’)
else - 向训练文件中添加对象
append_ocr_trainf (ObjectSelected, Image, ClassNames[j - 1], ‘train_characters_ocr.trf’)
endif
dev_set_color (‘gray’)
dev_display (ObjectSelected)
disp_message (WindowHandle, ClassNames[j - 1], ‘window’, 10, 10 + (j * 20), ‘black’, ‘true’)
endfor
disp_continue_message (WindowHandle, ‘black’, ‘true’)
stop ()
endfor
读训练文件并转化为图像
read_ocr_trainf (Characters, ‘train_characters_ocr.trf’, CharacterNames)
count_obj (Characters, NumberCharacters)
- 将训练字符储存到指定文件
- 对元素进行计数
for i := 1 to NumberCharacters by 1
select_obj (Characters, CharacterSelected, i)
dev_clear_window ()
dev_display (CharacterSelected)
disp_message (WindowHandle, CharacterNames[i - 1], ‘window’, 10, 10, ‘black’, ‘true’)
endfor
- 训练OCR分类器
trainf_ocr_class_svm (OCRHandle, ‘train_characters_ocr.trf’, 0.001, ‘default’) - 缩减SVM分类器,以减少分类所用时间。
reduce_ocr_class_svm (OCRHandle, ‘bottom_up’, 2, 0.001, OCRHandleReduced) - 将训练出的分类器写入文件
write_ocr_class_svm (OCRHandleReduced, ‘font_characters_ocr’) - 清除OCR分类器
clear_ocr_class_svm (OCRHandle)
clear_ocr_class_svm (OCRHandleReduced)
stop ()
dev_clear_window ()
disp_message (WindowHandle, ‘No more lines to execute’, ‘window’, 10, 10, ‘black’, ‘true’)
处理思路
这个例子是主要讲解了如何使用,SVM分类器进行OCR字符训练。
后记
大家有什么问题可以向我提问哈,我看到了第一时间回复,希望在学习的路上多多结交良师益友。