字符存储.PNG

如上图,创建文件夹,分别存储需要训练的字符图片。


代码如下:

dev_set_draw ('margin')

*将0-9、A-Z存入字符数组中

CharH := []

for i := 0 to 9 by 1

   CharH[i] := chr(round(i + ord('0')))

endfor

for i := 10 to 36-1 by 1

   CharH[i] := chr(round(i-10 + ord('A')))

endfor

NumChar := |CharH|


TrainFile := 'D:/IPI/Halcon12Projects/字符训练.trf'

for Indexfile:=0 to |CharH| - 1 by 1

    Path:='D:\\IPI\\训练0-9A-Z\\'+CharH[Indexfile]

    list_files (Path, 'files', ImageFiles)

    for Index := 0 to |ImageFiles|-1 by 1

        read_image (Image, ImageFiles[Index])

        *将字符添加到训练文件中

        append_ocr_trainf(Image,Image,CharH[Indexfile],TrainFile)

    endfor

endfor


*查询训练文件中的字符

read_ocr_trainf_names (TrainFile, CharacterNames, CharacterCount)

*创建OCR分类器

create_ocr_class_svm (8, 10, 'constant', 'default', CharacterNames, 'rbf', 0.02, 0.001, 'one-versus-one', 'normalization', 0, OCRHandle)

*训练

trainf_ocr_class_svm (OCRHandle, TrainFile, 0.001, 'default')

*写入本地

FontFile := 'D:/IPI/Halcon12Projects/字符训练.omc'

write_ocr_class_svm(OCRHandle,FontFile)

* 释放内存

clear_ocr_class_svm (OCRHandle)


*使用自己创建的分类器进行字符识别

*读取本地分类器

read_ocr_class_svm (FontFile, OCRHandle)

*字符识别

list_files ('D:/IPI/字符测试','files', Files)

for Index := 0 to |Files|-1 by 1

    read_image (Image, Files[Index])

    do_ocr_single_class_svm( Image, Image, OCRHandle, 1, Class)

    disp_message (3600, Class, 'window', 40, 221, 'black', 'true')

endfor

clear_ocr_class_svm (OCRHandle)

***************************************完***********************************************




***************************使用分类器识别*********************************

* read_image(Image,'C:/Users/研发/Pictures/Camera Roll/无标题.png')

* draw_rectangle1 (3600, Row1, Column1, Row2, Column2)

* gen_rectangle1(Rectangle, Row1, Column1, Row2, Column2)

* reduce_domain(Image, Rectangle, ImageReduced)

* threshold (ImageReduced, Region, 0, 128)

* connection (Region, ConnectedRegions)

* select_shape (ConnectedRegions, SelectedRegions, 'area', 'and', 15, 99999)

* sort_region (SelectedRegions, SortedRegions, 'first_point', 'true', 'row')

* shape_trans (SortedRegions,RegionTrans,'rectangle1')

* count_obj (RegionTrans, Number)

* area_center (RegionTrans, Area, Row, Column)

*读取训练的分类器

* read_ocr_class_mlp ('D:/IPI/Halcon12Projects/字符训练.omc',OcrHandle)

*识别

* for i:=0 to Number-1 by 1

*     do_ocr_multi_class_mlp (SortedRegions, ImageReduced, OcrHandle, Class, Confidence)

*     disp_message (3600, Class[i], 'window', Row[i]+40, Column[i], 'black', 'true')

* endfor

* clear_ocr_class_mlp (OcrHandle)




PS:本文参考网络及书籍