OCR光學字元識別
一、步驟 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訓練分類器,用write_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 分割字元
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_left', 'true', 'column') count_obj(SortedRegions, Number) for Index := 1 to Number by 1 dev_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.trf' dev_set_check('~give_error') delete_file(TrainFile) dev_set_check('~give_error') 1.4 將影象字元與字元標識關聯,儲存到訓練影象中 for i:=1 to Number by 1 select_obj(SortedRegions, SingleWord, i) append_ocr_trainf(SingleWord,Image,words[i-1],TrainFile) endfor (2)訓練OCR 2.1 確定字型檔名 FontFile:='words.omc' 2.2 得到字元標識名 read_ocr_trainf_names(TrainFile, CharacterNames, CharacterCount) 2.3 確定神經網路隱藏層節點數 NumHidden:=20 2.4 建立神經網路分類器 create_ocr_class_mlp(8, 10, 'constant', 'default', CharacterNames, 80, 'none', 10, 42, OCRHandle) 2.5 訓練神經網路 trainf_ocr_class_mlp(OCRHandle, TrainFile, 200, 1, 0.01, Error, ErrorLog) 2.6 儲存訓練結果 write_ocr_class_mlp(OCRHandle, FontFile) 2.7 清除控制代碼 clear_ocr_class_mlp(OCRHandle) (3)識別文字 3.1 讀入影象 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, -OrientationAngle/rad(180)*180, 'constant') 3.3 分割文字
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(TestWordsSortedRegions, 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, Class[Index-1], 'image', 12, 20*Index, 'green', 'true') stop() endfor clear_ocr_class_mlp (OCRHandle1)