1、Halcon OCR 总结By 17003步骤:1. 创建训练文件,将文字图像与文字分类标识关联,保存到训练文件中,训练文件后缀名为 trf,主要用到函数为 append_ocr_trainf。2. 训练 OCR 分类器,Halcon 支持 BOX 分类器、神经网络分类器(MLP)和支持向量机分类器(SVM) ,由于后两者比前者更加强大,推荐使用后两者。训练分类器非常简单,首先调用 create_ocr_class_mlp 或 create_ocr_class_svm 创建分类器,然后调用trainf_ocr_class_mlp 或 trainf_ocr_class_svm 训练分类器,用 w
2、rite_ocr_class_mlp 或write_ocr_class_svm 可以保存训练结果。3. 测试分类器,读入图像,如要文字不是水平,应将其旋转成水平,可以使用以下函数:text_line_orientation 计算文字倾角, rotate_image 旋转图像。注意前者使用的是弧度,后角使用的是度。分割文字。读取分类器 read_ocr_class_mlp,即读取训练分类器的结果。使用 do_ocr_multi_class_mlp 对文字进行识别。参考以下实例:为方便起见,这里将三个步骤放在一个实例里,也可以分别将三个步骤保存成三个独立的程序。*1 创建训练文件*1.1 分割字符
3、dev_close_window()read_image(Image,F:/学习资料/Halcon 工程/ocr-train.bmp)get_image_size(Image, Width, Height)dev_open_window(0, 0, Width, Height, black, WindowHandle)dev_display(Image)threshold(Image, Region, 0, 100)connection(Region, ConnectedRegions)sort_region (ConnectedRegions, SortedRegions, upper_le
4、ft, true, column)count_obj(SortedRegions, Number)for Index := 1 to Number by 1dev_clear_window()select_obj(SortedRegions, SingleWord, Index)dev_display(SingleWord)stop()endfor*1.2 文字分类标识 words:=a,b,c,d,e,f,g*1.3 创建训练文件TrainFile:=words.trfdev_set_check(give_error)delete_file(TrainFile)dev_set_check(g
5、ive_error)*1.4 将图像字符与字符标识关联,保存到训练图像中for i:=1 to Number by 1select_obj(SortedRegions, SingleWord, i)append_ocr_trainf(SingleWord,Image,wordsi-1,TrainFile)endfor*2 训练 OCR*2.1 确定字体文件名FontFile:=words.omc*2.2 得到字符标识名read_ocr_trainf_names(TrainFile, CharacterNames, CharacterCount)*2.3 确定神经网络隐藏层节点数NumHidde
6、n:=20*2.4 创建神经网络分类器create_ocr_class_mlp(8, 10, constant, default, CharacterNames, 80, none, 10, 42, OCRHandle)*2.4 训练神经网络trainf_ocr_class_mlp(OCRHandle, TrainFile, 200, 1, 0.01, Error, ErrorLog)*2.5 保存训练结果write_ocr_class_mlp(OCRHandle, FontFile)*2.6 清除句柄clear_ocr_class_mlp(OCRHandle)*3 识别文字*3.1 读入图像
7、dev_close_window()read_image(Image,F:/学习资料/Halcon 工程/ocr-read.bmp)get_image_size(Image, Width, Height)dev_open_window(0, 0, Width, Height, black, WindowHandle)dev_display(Image)*3.2 对齐文字text_line_orientation(Image, Image, 25, rad(-45), rad(45), OrientationAngle)rotate_image(Image, ImageRotate, -Orie
8、ntationAngle/rad(180)*180, constant)*分割文字threshold(ImageRotate, TestWordsRegion, 0,100)connection(TestWordsRegion, TestSingleWords)select_shape (TestSingleWords, SelectedRegions, area, and, 80, 500)sort_region (SelectedRegions, TestWordsSortedRegions, upper_left, true, column)count_obj(TestWordsSort
9、edRegions, Number)read_ocr_class_mlp(FontFile, OCRHandle1)do_ocr_multi_class_mlp(TestWordsSortedRegions, ImageRotate, OCRHandle1, Class, Confidence)for Index := 1 to Number by 1* dev_display(ImageRotate)select_obj(TestWordsSortedRegions, ObjectSelected, Index)dev_display(ObjectSelected)disp_message(WindowHandle, ClassIndex-1, image, 12, 20*Index, green, true)stop()endforclear_ocr_class_mlp (OCRHandle1) 附:训练图像测试图像