【问题标题】:How to read text from an image using OCR in android如何在android中使用OCR从图像中读取文本
【发布时间】:2013-01-02 12:01:38
【问题描述】:

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

但是当我运行这段代码时,我得到了以下错误:

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

我认为它指向以下行:

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

属于OCRServiceAPI 类。我该如何解决这个问题?

【问题讨论】:

    标签: android ocr


    【解决方案1】:

    无法猜测您的上述错误,但我已经在 Blackberry 中通过在 PHP上使用 OCR 的第三方应用程序 ABBYY 产品完成了这项任务> 服务器。

    在我长期的研发过程中,我还研究了Github_Abbyy 的以下链接。 要使用此代码,您应该在这里创建一个免费帐户:ocrsdk.com

    【讨论】:

      【解决方案2】:

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

      编辑:具体不包括org.apache.http.entity的子包,只包括实体包本身。

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

      【讨论】:

      【解决方案3】:

      检查您是否获得了从图库中选择的图像的正确路径。

      我也试过这个演示,它对我来说很好。

      我在这里发布我的代码:

      • 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;
        }   }
        

      【讨论】:

      • 像 /mnt/sdcard/_ExternalSD/DCIM/100LGDSC/xxxx.jpg 一样给出。对吗?
      • 您可以在这里发布您的工作代码,以便我纠正我的问题吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多