2013-01-02 2 views
2

Android에서 OCR을 구현하고 싶습니다. 나는. 명함 이미지에서 텍스트 가져 오기. here의 코드를 사용했습니다.android에서 OCR을 사용하여 이미지에서 텍스트를 읽는 방법

그러나 나는 다음과 같은 오류가있어이 코드를 실행하면

java.lang.NoClassDefFoundError: org.apache.http.entity.mime.content.FileBody

나는 그것이 다음 줄을 가리키는 생각하십시오 OCRServiceAPI 클래스의

final FileBody image = new FileBody(new File(filePath)); 

합니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

0

갤러리에서 이미지를 선택하고 있는지 여부를 확인하십시오.

나는 또한이 데모 및 저를 위해 잘 작동 해 봤습니다.

  • OCRServiceAPI.java

    public class OCRServiceAPI { 
    public final String m_serviceUrl = "http://api.ocrapiservice.com/1.0/rest/ocr"; 
    private final String m_paramImage = "image"; 
    private final String m_paramLanguage = "language"; 
    private final String m_paramApiKey = "apikey"; 
    private String m_apiKey, m_responseText; 
    private int m_responseCode; 
    public OCRServiceAPI(final String p_apiKey) { 
        this.m_apiKey = p_apiKey; 
    } 
    /* 
    * Convert image to text. 
    * 
    * @param language The image text language. 
    * 
    * @param filePath The image absolute file path. 
    * 
    * @return true if everything went okay and false if there is an error with 
    * sending and receiving data. 
    */ 
    public boolean convertToText(final String p_language, 
         final String p_filePath) { 
        try { 
         sendImage(p_language, p_filePath); 
         return true; 
        } catch (ClientProtocolException e) { 
         e.printStackTrace(); 
         return false; 
        } catch (IOException e) { 
         e.printStackTrace(); 
         return false; 
        } 
    } 
    /* 
    * Send image to OCR service and read response. 
    * 
    * @param language The image text language. 
    * 
    * @param filePath The image absolute file path. 
    */ 
    private void sendImage(final String p_language, final String p_filePath) 
         throws ClientProtocolException, IOException { 
        final HttpClient m_httpclient = new DefaultHttpClient(); 
        final HttpPost m_httppost = new HttpPost(m_serviceUrl); 
        final FileBody m_image = new FileBody(new File(p_filePath)); 
        final MultipartEntity m_reqEntity = new MultipartEntity(); 
        m_reqEntity.addPart(m_paramImage, m_image); 
        m_reqEntity.addPart(m_paramLanguage, new StringBody(p_language)); 
        m_reqEntity.addPart(m_paramApiKey, new StringBody(getApiKey())); 
        m_httppost.setEntity(m_reqEntity); 
        final HttpResponse m_response = m_httpclient.execute(m_httppost); 
        final HttpEntity m_resEntity = m_response.getEntity(); 
        final StringBuilder m_sb = new StringBuilder(); 
        if (m_resEntity != null) { 
         final InputStream m_stream = m_resEntity.getContent(); 
         byte m_bytes[] = new byte[4096]; 
         int m_numBytes; 
         while ((m_numBytes = m_stream.read(m_bytes)) != -1) { 
          if (m_numBytes != 0) { 
           m_sb.append(new String(m_bytes, 0, m_numBytes)); 
          } 
         } 
        } 
        setResponseCode(m_response.getStatusLine().getStatusCode()); 
        setResponseText(m_sb.toString()); 
    } 
    public int getResponseCode() { 
        return m_responseCode; 
    } 
    public void setResponseCode(int p_responseCode) { 
        this.m_responseCode = p_responseCode; 
    } 
    public String getResponseText() { 
        return m_responseText; 
    } 
    public void setResponseText(String p_responseText) { 
        this.m_responseText = p_responseText; 
    } 
    public String getApiKey() { 
        return m_apiKey; 
    } 
    public void setApiKey(String p_apiKey) { 
        this.m_apiKey = p_apiKey; 
    } } 
    
  • SampleActivity.java

    public class SampleActivity extends Activity implements OnClickListener { 
    private final int RESPONSE_OK = 200; 
    private final int IMAGE_PICKER_REQUEST = 1; 
    private TextView m_tvPicNameText; 
    private EditText m_etLangCodeField, m_etApiKeyFiled; 
    private String m_apiKey; // T7GNRh7VmH 
    private String m_langCode; // en 
    private String m_fileName; 
    @Override 
    public void onCreate(Bundle p_savedInstanceState) { 
        super.onCreate(p_savedInstanceState); 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
          WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        setContentView(R.layout.main); 
        m_tvPicNameText = (TextView) findViewById(R.id.imageName); 
        m_etLangCodeField = (EditText) findViewById(R.id.lanuageCode); 
        m_etApiKeyFiled = (EditText) findViewById(R.id.apiKey); 
        m_etApiKeyFiled.setText("T7GNRh7VmH"); 
        final Button m_btnPickImage = (Button) findViewById(R.id.picImagebutton); 
        m_btnPickImage.setOnClickListener(new OnClickListener() { 
         public void onClick(View v) { 
          // Starting image picker activity 
          startActivityForResult(
            new Intent(
              Intent.ACTION_PICK, 
              android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI), 
            IMAGE_PICKER_REQUEST); 
         } 
        }); 
        final Button m_btnConvertText = (Button) findViewById(R.id.convert); 
        m_btnConvertText.setOnClickListener(this); 
    } 
    public void onClick(View p_v) { 
        m_apiKey = m_etApiKeyFiled.getText().toString(); 
        m_langCode = m_etLangCodeField.getText().toString(); 
        // Checking are all fields set 
        if (m_fileName != null && !m_apiKey.equals("") 
          && !m_langCode.equals("")) { 
         final ProgressDialog m_prgDialog = ProgressDialog.show(
           SampleActivity.this, "Loading ...", "Converting to text.", 
           true, false); 
         final Thread m_thread = new Thread(new Runnable() { 
          public void run() { 
           final OCRServiceAPI m_apiClient = new OCRServiceAPI(
             m_apiKey); 
           m_apiClient.convertToText(m_langCode, m_fileName); 
           // Doing UI related code in UI thread 
           runOnUiThread(new Runnable() { 
            public void run() { 
             m_prgDialog.dismiss(); 
             // Showing response dialog 
             final AlertDialog.Builder m_alert = new AlertDialog.Builder(
               SampleActivity.this); 
             m_alert.setMessage(m_apiClient.getResponseText()); 
             m_alert.setPositiveButton("OK", 
               new DialogInterface.OnClickListener() { 
                public void onClick(
                  DialogInterface p_dialog, 
                  int p_id) { 
                } 
               }); 
             // Setting dialog title related from response code 
             if (m_apiClient.getResponseCode() == RESPONSE_OK) { 
              m_alert.setTitle("Success"); 
             } else { 
              m_alert.setTitle("Faild"); 
             } 
             m_alert.show(); 
            } 
           }); 
          } 
         }); 
         m_thread.start(); 
        } else { 
         Toast.makeText(SampleActivity.this, "All data are required.", 
           Toast.LENGTH_SHORT).show(); 
        } 
    } 
    @Override 
    protected void onActivityResult(int p_requestCode, int p_resultCode, 
         Intent p_data) { 
        super.onActivityResult(p_requestCode, p_resultCode, p_data); 
        if (p_requestCode == IMAGE_PICKER_REQUEST && p_resultCode == RESULT_OK) { 
         m_fileName = getRealPathFromURI(p_data.getData()); 
         m_tvPicNameText.setText("Selected: en" 
           + getStringNameFromRealPath(m_fileName)); 
        } 
    } 
    /* 
    * Returns image real path. 
    */ 
    private String getRealPathFromURI(final Uri p_contentUri) { 
        final String[] m_proj = { MediaStore.Images.Media.DATA }; 
        final Cursor m_cursor = managedQuery(p_contentUri, m_proj, null, null, 
          null); 
        int m_columnIndex = m_cursor 
          .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
        m_cursor.moveToFirst(); 
        return m_cursor.getString(m_columnIndex); 
    } 
    /* 
    * Cuts selected file name from real path to show in screen. 
    */ 
    private String getStringNameFromRealPath(final String bucketName) { 
        return bucketName.lastIndexOf('/') > 0 ? bucketName 
          .substring(bucketName.lastIndexOf('/') + 1) : bucketName; 
    } } 
    
+0

ive는 /mnt/sdcard/_ExternalSD/DCIM/100LGDSC/xxxx.jpg와 같습니다. 맞아? – sanjay

+0

내 문제를 해결할 수 있도록 여기에 작업 코드를 게시 할 수 있습니까? – sanjay

2

이 위의 오류에 대해 추측 할 수 있지만, 내가 가진 : 여기

내 코드를 게시하도록하겠습니다 이것을했다 작업 검은 딸기 타사 응용 프로그램을 사용하여 ABBYY OCR의 제품 PHP 서버.

나는 오랫동안 R & D 중에 Github_Abbyy 링크도 작업했습니다. 이 코드를 사용하려면 다음 위치에서 무료 계정을 만들어야합니다.

0

모든 Apache 패키지는 기본적으로 Android에서 사용할 수 없으므로 Apache 저장소에서 다운로드해야합니다. 질문 Android libraries not found과 그 답에 제공된 링크를보십시오.

편집 : 특히 org.apache.http.entity의 하위 패키지는 엔티티 패키지 자체에 포함되지 않습니다.

OCR API에서 제공 한 예제 프로젝트에서는 mime 패키지를 jar에 넣습니다 (in the lib folder).

+0

필자는 이미 httpmine.jar 파일을 잘 참조했습니다. 그러나 성공하지 못했습니다. – sanjay

+0

이클립스 (Eclipse를 사용하고 있습니까?)가 APK에 라이브러리를 자동으로 배치하는 것을 처리 할 것이라고 생각합니다. 하나의 옵션은 다른 클래스 로더를 사용하고 필요하기 전에 해당 클래스를 동적으로로드하는 것입니다 (그러나 이것이 필요한 이유는 알 수 없습니다). 참고 자료 : [Android에서 JAR로부터 클래스로드하기] (http://stackoverflow.com/questions/11929850/loading-classes-from-jar-on-android) – Sardtok

+0

[Eclipse 프로젝트에 jar를 포함하는 방법] (http : //stackoverflow.com/a/11824038/1935704) – Sardtok

관련 문제