halcon OCR识别,训练自己的OCR

看halcon助手有OCR识别,就想着试一下,结果一直识别不出来,不知道怎么训练自己的OCR库,经过一天搜索资料,终于知道怎么训练自己的OCR库,并在图像中进行识别
害怕以后忘了,上传上来以备以后不时之需

dev_set_draw (‘margin’)
*加载图像
read_image (Image, ‘汉字识别.jpg’)
*选取感兴趣区域,本例训练‘中华人民共和国’几个汉字
gen_rectangle1 (Rectangle1, 134, 187, 188, 418)
reduce_domain (Image, Rectangle1, ImageReduced)
*图像预处理
dev_set_draw (‘fill’)
threshold (ImageReduced, Regions, 0, 200)
connection (Regions, ConnectedRegions)

*对于‘共’这种分开的字符,sort_region可通过’character’参数识别成一个字符
sort_region (ConnectedRegions, SortedRegions, ‘character’, ‘true’, ‘column’)
count_obj (SortedRegions, Number)

word := [‘中’,‘华’,‘人’,‘民’,‘共’,‘和’,‘国’]
TrainFile:=‘MyTrainTest汉字.trf’
dev_set_check (’~give_error’)
delete_file (TrainFile)
dev_set_check (’~give_error’)

MaxHeight:=9
MaxWidth:=11
for Index := 1 to Number by 1
select_obj (SortedRegions, ObjectSelected, Index)
*将训练字符添加到测试文件中
append_ocr_trainf (ObjectSelected, Image, word[Index-1], TrainFile)
*以下内容可删除,便于后面确定显示位置
shape_trans (ObjectSelected, RegionTrans, ‘rectangle1’)
dev_display (RegionTrans)
region_features (RegionTrans, ‘width’, width)
region_features (RegionTrans, ‘height’, height)
if (|width| > MaxWidth)
width:=MaxWidth
endif
if (|height| > MaxHeight)
height:=MaxHeight
endif
endfor
stop ()

FontFile:=‘MyTrainTest汉字.omc’
*查询哪些字符存储在测试文件中
read_ocr_trainf_names (TrainFile, CharacterNames1, CharacterCount1)
*利用MLP(多层感知器)创建一个新的OCR分级器
create_ocr_class_mlp (MaxWidth, MaxHeight, ‘constant’, ‘default’, word, 80, ‘none’, 10, 42, OCRHandle)
*测试OCR分级器的OCRHandle,根据存储在OCR文件中的测试特性
trainf_ocr_class_mlp (OCRHandle, TrainFile, 200, 1, 0.01, Error1, ErrorLog1)
*将OCR分级器的OCRHandle写入由文件名确定的文件中
write_ocr_class_mlp (OCRHandle, FontFile)
*清除所有的由OCRHandle给定的且由create_ocr_class_mlp创建的OCR分级器,释放所有的分级器占据的存储空间
clear_ocr_class_mlp (OCRHandle)

*以上,字符训练完毕,下面开始进行字符识别

*经测试,识别正确,分数都在0.99以上,低于0.99一般都是识别错误
MinScore:=0.992
*加载即将识别的图像
read_image (Image1, ‘汉字识别.jpg’)
*图像预处理
threshold (Image1, Region, 0, 200)
connection (Region, ConnectedRegions1)
select_shape (ConnectedRegions1, SelectedRegions1, ‘area’, ‘and’, 45, 160)
sort_region (SelectedRegions1, SortedRegions1, ‘first_point’, ‘true’, ‘row’)
area_center (SortedRegions1, Area, Row, Column)

*从一个文件中读取OCR分级器
read_ocr_class_mlp (FontFile, OCRHandle1)
*为根据给定区域字符和OCR分级器OCRHandle的灰度图像值而给定的每个字符计算出最好的类,将类返回到Class中,且将类的置信度返回到Confidence中
do_ocr_multi_class_mlp (SortedRegions1, Image1, OCRHandle1, RecNum, Confidence)

*显示在屏幕上
dev_display (Image1)
OffsetX:=10
OffsetY:=6
dev_set_draw (‘margin’)
for i := 0 to |RecNum| - 1 by 1
RowBegin:=Row[i]+OffsetX
ColumnBegin:=Column[i]-OffsetY
if (Confidence[i]<MinScore)
*未识别出来,显示X
set_tposition (3600, RowBegin, ColumnBegin)
write_string (3600, ‘X’)
else
*识别成功,显示该字符
set_tposition (3600, RowBegin, ColumnBegin)
write_string (3600, RecNum[i])
endif
endfor

stop 在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/dazhuan0429/article/details/84991610