개발 환경 : windows 10, Adroid Studio 3.0.1, 갤럭시 노트 8(API 28, Android 9)

 

Tesseract는 구글에서 제공하는 문자 인식 관련 오픈소스입니다.

 

오픈소스이므로 직접 언어 데이터를 개선 및 발전에 직접 참여할 수 있습니다.

지속적으로 최신 버전이 출시되고 있습니다.

 

언어 데이터는 아래 링크에서 다운로드 가능합니다.

깃허브에서 배포 중입니다.

https://github.com/tesseract-ocr/tessdata

 

tesseract-ocr/tessdata

Contribute to tesseract-ocr/tessdata development by creating an account on GitHub.

github.com

 

먼저 안드로이드 프로젝트를 생성하고 Modul.app 단에 아래의 코드를 추가합니다.

dependencies {
	implementation 'com.rmtheis:tess-two:6.3.0'
}

만약 tess의 최신버진이 존재할 경우 이 보다 최신 버전의 코드를 작성해도됩니다.

 

이후 위 링크에서 언어 데이터를 다운로드합니다.

 

저는 kor(한글)과 eng(영어)를 다운로드 했습니다.

다운로드 이후 아래처럼 assets 폴더 아래에 tessdata 폴더 생성 후 방금 다운로드한 언어 데이터를 저장합니다.

 

이후 문자를 인식해 추출할 이미지를 res/drawable 폴더에 아래처럼 저장합니다.

저는 test.png에서 문자를 추출할 것입니다.

 

먼저 아래와 같은 전역변수를 선언합니다.

TessBaseAPI tess;
String dataPath = "";

 

이후 MainActivity에서 동작할 코드를 작성합니다.

먼저 onCreate에서 파일 체크 및 객체 초기화를 수행합니다. 이후 문자 인식을 진행합니다.

주석을 참고하면 됩니다.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

	// 데이터 경로
        dataPath = getFilesDir()+ "/tesseract/";
        
	// 한글 & 영어 데이터 체크
        checkFile(new File(dataPath + "tessdata/"), "kor");
        checkFile(new File(dataPath + "tessdata/"), "eng");

	// 문자 인식을 수행할 tess 객체 생성
        String lang = "kor+eng";
        tess = new TessBaseAPI();
        tess.init(dataPath, lang);

	//문자 인식 진행
        processImage(BitmapFactory.decodeResource(getResources(), R.drawable.test));
    }

 

 

이후 각 함수를 정의합니다.

// 문자 인식 및 결과 출력
public void processImage(Bitmap bitmap){
        Toast.makeText(getApplicationContext(), "이미지가 복잡할 경우 해석 시 많은 시간이 소요될 수도 있습니다.", Toast.LENGTH_LONG).show();
        String OCRresult = null;
        tess.setImage(bitmap);
        OCRresult = tess.getUTF8Text();
        TextView OCRTextView = (TextView) findViewById(R.id.tv_result);

        OCRTextView.setText(OCRresult);
    }

 

// 파일 복제 
private void copyFiles(String lang) {
        try {
            //location we want the file to be at
            String filepath = dataPath + "/tessdata/" + lang + ".traineddata";

            //get access to AssetManager
            AssetManager assetManager = getAssets();

            //open byte streams for reading/writing
            InputStream inStream = assetManager.open("tessdata/" + lang + ".traineddata");
            OutputStream outStream = new FileOutputStream(filepath);

            //copy the file to the location specified by filepath
            byte[] buffer = new byte[1024];
            int read;
            while ((read = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, read);
            }
            outStream.flush();
            outStream.close();
            inStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

// 파일 존재 확인
private void checkFile(File dir, String lang) {
        //directory does not exist, but we can successfully create it
        if (!dir.exists()&& dir.mkdirs()){
            copyFiles(lang);
        }
        //The directory exists, but there is no data file in it
        if(dir.exists()) {
            String datafilePath = dataPath+ "/tessdata/" + lang + ".traineddata";
            File datafile = new File(datafilePath);
            if (!datafile.exists()) {
                copyFiles(lang);
            }
        }
    }

 

이제 프로그램을 실행하면 tess 객체에 의해 이미지에서 문자가 추출되고 TextView에 결과가 출력됩니다.

test.png

결과

영어의 인식률과 정확도는 굉장히 높은 편인 것을 볼 수 있습니다.

한글의 경우 인식률과 정확도가 영어에 비해 떨어집니다.

 

하지만 오픈소스이고 개선 참여 및 배포가 가능하니 OCR에 관심이 있는 분들은 아래 링크에서 개선에 참여해보세요.

https://github.com/tesseract-ocr/tesseract

 

tesseract-ocr/tesseract

Tesseract Open Source OCR Engine (main repository) - tesseract-ocr/tesseract

github.com

 

'IT > 안드로이드' 카테고리의 다른 글

안드로이드 팝업 알림  (1) 2017.09.22
안드로이드 동영상 배경화면 만들기  (2) 2017.07.17
안드로이드 ListView 클릭 안될 때  (3) 2017.07.14

+ Recent posts