如何在android中使用OCR从图像中读取文本

时间:2013-01-02 12:01:38

标签: android ocr

我想在Android中实现OCR。即从名片图像中获取文本。我使用了来自here的代码。

但是当我运行此代码时,我收到以下错误:

  

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

我认为它指向以下一行:

final FileBody image = new FileBody(new File(filePath));
OCRServiceAPI类的

。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

无法猜测您的上述错误,但我已在错误> 中使用第三方应用 ABBYY OCR产品在 Blackberry 中完成此任务>服务器。

在我长期的R& D我还参与了Github_Abbyy的以下链接。 要使用此代码,您应在此处创建免费帐户:ocrsdk.com

答案 1 :(得分: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;
    }   }
    

答案 2 :(得分:0)

默认情况下,Android中并非所有Apache软件包都可用,因此您必须从Apache存储库下载它们并自行包含它们。请参阅问题Android libraries not found以及答案中提供的链接。

编辑:具体来说,org.apache.http.entity的子包不包含在内,只包含实体包本身。

在OCR API提供的示例项目中,他们将mime包放在jar in the lib folder中。