標籤:
(轉載請註明出處:http://blog.csdn.net/buptgshengod)
1.介紹
快過年了,博主的新應用-螢幕取詞之了老花鏡的編碼工作也在緊鑼密鼓的進行中。下面分享一下這個應用中的核心功能ocr,也就是圖片識詞功能。先來看下我的實現效果。是在網上隨便截下來的一個帶有英文的頁面,是我的應用程式的實現效果。
2.實現
(1)首先要下載我的源碼和語言套件,部落格下方會給出地址。(源碼設為10分,是想讓大家珍惜別人的勞動成果)
(2)把代碼中的lib中的兩個檔案夾和jar檔案匯入。
(3)需要注意的有兩點請認真看下面貼出的代碼的注釋
[java] view plaincopy
- package com.example.tess;
-
-
- import java.io.File;
-
- import com.googlecode.tesseract.android.TessBaseAPI;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.Intent;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class MainActivity extends Activity {
-
- private TextView text;
- TessBaseAPI baseApi;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- Button bt=new Button(getBaseContext());
- bt=(Button)findViewById(R.id.button1);
-
- text=new TextView(getBaseContext());
- text=(TextView)findViewById(R.id.textView1);
-
- baseApi=new TessBaseAPI();
- //(注意)前面的地址是語言套件的父級。eng表示解析的是英文
- baseApi.init("/mnt/sdcard/tesseract/", "eng");
-
- bt.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View sourse) {
- // text.setText("sb");
- //設定要ocr的圖片bitmap,要解析的圖片地址(注意)
- baseApi.setImage(getDiskBitmap("/mnt/sdcard/mypic.bmp"));
- //根據Init的語言,獲得ocr後的字串
- String text1= baseApi.getUTF8Text();
- text.setText(text1);
- //釋放bitmap
- baseApi.clear();
- }
- }
- );
- }
- /*
- * 將本地圖片轉換為bitmap
- */
-
- private Bitmap getDiskBitmap(String pathString)
- {
- Bitmap bitmap = null;
- try
- {
- File file = new File(pathString);
- if(file.exists())
- {
- bitmap = BitmapFactory.decodeFile(pathString);
-
- }
- } catch (Exception e)
- {
- // TODO: handle exception
- }
-
-
- return bitmap;
- }
- }
(4)圖片越大耗時越長,本例耗時差不多半分鐘
3.源碼及相關檔案
好吧,好多人說代碼下載不了或者說10分太貴了,這裡提供一下免費。其中tess檔案夾是android程式tessdata是語言套件
4.中文識別
可到以下地址下載,將其解壓放到/tesseract/tessdata下面,然後將eng改為chi_sim
http://code.google.com/p/tesseract-ocr/downloads/detail?name=chi_sim.traineddata.gz&can=2&q=
android tesseract-ocr執行個體教程(包含中文識別)(附源碼)