1、登录百度AI平台(https://ai.baidu.com/),下载license文件
包名填写内容:
下载好的文件夹内包含四个文件
(OCR-Android-SDK.md文件里有使用说明)
(1)将libs文件夹下的ocr-sdk.jar拷贝到工程目录中
找到工程存储的文件夹,依次打开app -> libs -> 将jar包拷贝到libs文件夹下
(2)加入工程依赖
File -> Project Structure -> Dependencies -> (在Modules栏)选中app -> (在Declared Dependencies栏)点击“+” -> 选择“jar dependence”
选中刚才导入的jar
(3)将libs目录下armeabi,arm64-v8a,armeabi-v7a,x86文件夹按需添加到android studio工程src/main/jniLibs
目录中
(4)将在百度平台上下载下来的api.license文件添加到工程的assets文件夹
找到工程所在的文件夹,依次打开app -> src -> main-> 新建文件夹 assets -> 将license文件放在assets文件夹中
2、在AndroidManifest.xml中添加以下权限
3、在oncreate()方法里初始化OCR单例
//初始化OCR单例/
OCR.getInstance(getApplication()).initAccessToken(new OnResultListener() {
public void onResult(AccessToken result) {
// 调用成功,getApplication()返回AccessToken对象
String token = result.getAccessToken();
}
@Override
public void onResult(Object o) {
}
@Override
public void onError(OCRError error) {
// 调用失败,返回OCRError子类SDKError对象
} }, getApplicationContext());
//
在oncreate()方法里定义按钮的点击事件
gray=findViewById(R.id.gray);
gray.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//convert2Gray();
//ocrNormal();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File outImage=new File(getExternalCacheDir(),timeStamp+"output_image.jpg");
try{
if(outImage.exists())
{
outImage.delete();
}
outImage.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
if(Build.VERSION.SDK_INT>=24)
{
uri= FileProvider.getUriForFile(MainActivity.this,"com.example.demo_tryopencv_2.fileprovider",outImage);
}
else
{
uri=Uri.fromFile(outImage);
}
Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
startActivityForResult(intent,TAKE_POTHO);
}
});
/
代码展示(先调用摄像头拍摄,再将拍摄图片用来识别文字)
/**
* 拍照
*/
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
if (Build.VERSION.SDK_INT >= 23) {
int REQUEST_CODE_CONTACT = 101;
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//验证是否许可权限
for (String str : permissions) {
if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
//申请权限
this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
}
}
}
super.onActivityResult(requestCode,resultCode,data);
switch (requestCode)
{
case TAKE_POTHO:
if(resultCode==RESULT_OK)
{
try{
Bitmap bitmap= BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
pic=(ImageView)findViewById(R.id.pic);
pic.setImageBitmap(bitmap);
ocrNormal(bitmap);
}catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
break;
default:
break;
}
}
public File compressImage(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
/* int options = 100;
while (baos.toByteArray().length / 1024 > 20) { //循环判断如果压缩后图片是否大于20kb,大于继续压缩 友盟缩略图要求不大于18kb
baos.reset();//重置baos即清空baos
options -= 10;//每次都减少10
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
long length = baos.toByteArray().length;
}*/
if (Build.VERSION.SDK_INT >= 23) {
int REQUEST_CODE_CONTACT = 101;
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//验证是否许可权限
for (String str : permissions) {
if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
//申请权限
this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
}
}
}
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(System.currentTimeMillis());
//图片名
String filename = format.format(date);
File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.d("=-=-=-=-=-", "compressImage: " + file);
// recycleBitmap(bitmap);
return file;
}
private void ocrNormal(Bitmap bitmap) {
text=findViewById(R.id.text);
// 通用文字识别参数设置
GeneralBasicParams param = new GeneralBasicParams();
param.setDetectDirection(true);
//这里调用的是本地文件,使用时替换成你的本地文件
File file;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(System.currentTimeMillis());
//图片名
String filename = format.format(date);
file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
param.setImageFile(file);
// 调用通用文字识别服务
OCR.getInstance(getApplication()).recognizeAccurateBasic(param, new OnResultListener() {
@Override
public void onResult(GeneralResult result) {
StringBuilder sb = new StringBuilder();
// 调用成功,返回GeneralResult对象
for (WordSimple wordSimple : result.getWordList()) {
// wordSimple不包含位置信息
WordSimple word = wordSimple;
sb.append(word.getWords());
//sb.append("\n");
}
//file.delete();
//String返回
String ocrResult = sb.toString();
Log.v("4","===================================="+ocrResult);
// json格式返回字符串result.getJsonRes())
// text.setText(ocrResult);
text.setText("成功了一大半"+ocrResult+"lalala");
}
@Override
public void onError(OCRError error) {
// 调用失败,返回OCRError对象
text.setText("出错啦");
Log.v("1","================================================"+error.getLocalizedMessage());
Log.v("2","================================================"+error.getMessage());
Log.v("3","================================================"+error.getErrorCode());
}
});
}