基于百度ai实现身份证,银行卡自动识别,车牌识别

1.创建应用 获取应用的API Key和Secret Key

2.下载SDK,将SDK的jar包和依赖包导入自己的项目。

3.下载License文件

4.初始化

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initAccessTokenWithAkSk();
} else {
Toast.makeText(getApplicationContext(), "需要android.permission.READ_PHONE_STATE", Toast.LENGTH_LONG).show();
}
}

private boolean checkTokenStatus() {
if (!hasGotToken) {
Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
}
return hasGotToken;
}

/**
* 以license文件方式初始化
*/
private void initAccessToken() {
OCR.getInstance(this).initAccessToken(new OnResultListener() {
@Override
public void onResult(AccessToken accessToken) {
String token = accessToken.getAccessToken();
hasGotToken = true;
}

@Override
public void onError(OCRError error) {
error.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MyZiliaoActivity.this, "licence方式获取token失败", Toast.LENGTH_SHORT).show();

}
});
}
}, getApplicationContext());
}

/**
* 用明文ak,sk初始化
*/
private void initAccessTokenWithAkSk() {
OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener() {
@Override
public void onResult(AccessToken result) {
String token = result.getAccessToken();
hasGotToken = true;
}

@Override
public void onError(OCRError error) {
error.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MyZiliaoActivity.this, "AK,SK方式获取token失败", Toast.LENGTH_SHORT).show();
}
});
}
}, getApplicationContext(), "xxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxx");
}

/**
* 自定义license的文件路径和文件名称,以license文件方式初始化
*/
private void initAccessTokenLicenseFile() {
OCR.getInstance(this).initAccessToken(new OnResultListener() {
@Override
public void onResult(AccessToken accessToken) {
String token = accessToken.getAccessToken();
hasGotToken = true;
}

@Override
public void onError(OCRError error) {
error.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MyZiliaoActivity.this, "自定义文件路径licence方式获取token失败", Toast.LENGTH_SHORT).show();

}
});
}
}, "aip.license", getApplicationContext());
}
}

身份证正面
Intent intent = new Intent(MyZiliaoActivity.this, CameraActivity.class);
intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
FileUtil.getSaveFile((getApplication()),1).getAbsolutePath());
intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
initAccessTokenWithAkSk();
身份证反面
Intent intent1 = new Intent(MyZiliaoActivity.this, CameraActivity.class);
intent1.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
FileUtil.getSaveFile((getApplication()),2).getAbsolutePath());
intent1.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
startActivityForResult(intent1, REQUEST_CODE_CAMERA);
initAccessTokenWithAkSk();

调用银行卡
Intent intent3 = new Intent(MyZiliaoActivity.this, CameraActivity.class);
intent3.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
FileUtil.getSaveFile(getApplication(),0).getAbsolutePath());
intent3.putExtra(CameraActivity.KEY_CONTENT_TYPE,
CameraActivity.CONTENT_TYPE_BANK_CARD);
startActivityForResult(intent3, REQUEST_CODE_BANKCARD);
调用车牌

Intent intent = new Intent(getActivity(), CameraActivity.class); intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, FileUtil.getSaveFile(getActivity().getApplication()).getAbsolutePath()); intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_GENERAL); startActivityForResult(intent, REQUEST_CODE_LICENSE_PLATE);

 

解析银行卡,身份证

private void recCreditCard(String filePath) {
// 银行卡识别参数设置
BankCardParams param = new BankCardParams();
param.setImageFile(new File(filePath));

// 调用银行卡识别服务
OCR.getInstance(this).recognizeBankCard(param, new OnResultListener() {
@Override
public void onResult(BankCardResult result) {
if (result != null) {
et_yinhangkahao.setText(result.getBankCardNumber());
// tv_yhk.setVisibility(View.VISIBLE);
// tv_yhk.setText(result.getBankCardNumber());

}

}
@Override
public void onError(OCRError error) {

Toast.makeText(MyZiliaoActivity.this, error.toString(), Toast.LENGTH_SHORT).show();

}
});
}

private void recIDCard(final String idCardSide, final String filePath) {
final IDCardParams param = new IDCardParams();
param.setImageFile(new File(filePath));
// 设置身份证正反面
param.setIdCardSide(idCardSide);
// 设置方向检测
param.setDetectDirection(true);
// 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
param.setImageQuality(40);
OCR.getInstance(this).recognizeIDCard(param, new OnResultListener() {
@Override
public void onResult(IDCardResult result) {
alertText("", result.toString());
if (result != null) {
String name = "";
String sex = "";
String num = "";
if (result.getName() != null) {
name = result.getName().toString();
}
if (result.getGender() != null) {
sex = result.getGender().toString();
}
if (result.getIdNumber() != null) {
num = result.getIdNumber().toString();
}
et_name.setText(name);
et_shenfenzheng.setText(num);
if (sex.equals("男")) {
rb_nan.setChecked(true);
rb_nv.setChecked(false);
} else if (sex.equals("女")) {
rb_nv.setChecked(true);
rb_nan.setChecked(false);
}


iv_zhengmian.setImageBitmap(null);
zhengmianFile = new File(filePath);
Uri image = Uri.fromFile(new File(String.valueOf(zhengmianFile)));
Picasso.with(MyZiliaoActivity.this).load(image)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.error(R.drawable.zhanwei)
.into(iv_zhengmian);
Log.i("正面", result.toString()+zhengmianFile.toString());

}
}

@Override
public void onError(OCRError error) {
Toast.makeText(MyZiliaoActivity.this, "识别出错,请查看log错误代码", Toast.LENGTH_SHORT).show();
Log.d("MainActivity", "onError: " + error.getMessage());
}
});
}

private void recIDCard1(String idCardSide, final String filePath) {
final IDCardParams param = new IDCardParams();
param.setImageFile(new File(filePath));
// 设置身份证正反面
param.setIdCardSide(idCardSide);
// 设置方向检测
param.setDetectDirection(true);
// 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
param.setImageQuality(40);
OCR.getInstance(this).recognizeIDCard(param, new OnResultListener() {
@Override
public void onResult(IDCardResult result) {
if (result != null) {
iv_fanmian.setImageBitmap(null);
fanmianFile = new File(filePath);
Uri image = Uri.fromFile(new File(String.valueOf(fanmianFile)));
Picasso.with(MyZiliaoActivity.this).load(image)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.error(R.drawable.zhanwei)
.into(iv_fanmian);
Log.i("反面", result.toString()+fanmianFile.toString());
}
}

@Override
public void onError(OCRError error) {
Toast.makeText(MyZiliaoActivity.this, "识别出错,请查看log错误代码", Toast.LENGTH_SHORT).show();
Log.d("MainActivity", "onError: " + error.getMessage());
}
});
}

private void chepai(final int i, final String filePath) {

        final OcrRequestParams  param= new OcrRequestParams();
        param.setImageFile(new File(filePath));
        OCR.getInstance(getActivity()).recognizeLicensePlate(param, new OnResultListener() {
            @Override
            public void onResult(OcrResponseResult ocrResponseResult) {

//                alertText("", result.toString());
                if (ocrResponseResult != null) {
                    String name = ocrResponseResult.getJsonRes();
                    Gson gson = new Gson();
                    JsonRootBean jsonBean = gson.fromJson(name, JsonRootBean.class);
                    et_chepaihao.setText(jsonBean.getWords_result().getNumber());

                    Log.i("车牌",name+"号码"+et_chepaihao.getText());
                    iv_photo.setImageBitmap(null);
                    finalFile = new File(filePath);
                    Uri image = Uri.fromFile(new File(String.valueOf(finalFile)));
                    Picasso.with(mActivity).load(image)
                            .memoryPolicy(MemoryPolicy.NO_CACHE)
                            .networkPolicy(NetworkPolicy.NO_CACHE)
                            .error(R.drawable.meiyoushuju)
                            .into(iv_photo);
                    Log.i("正面", ocrResponseResult.toString()+finalFile.toString());

                }
            }
            @Override
            public void onError(OCRError error) {
                iv_photo.setImageBitmap(null);
                finalFile = new File(filePath);
                Uri image = Uri.fromFile(new File(String.valueOf(finalFile)));
                Picasso.with(mActivity).load(image)
                        .memoryPolicy(MemoryPolicy.NO_CACHE)
                        .networkPolicy(NetworkPolicy.NO_CACHE)
                        .error(R.drawable.meiyoushuju)
                        .into(iv_photo);
//                Toast.makeText(mActivity, "识别出错,请查看log错误代码", Toast.LENGTH_SHORT).show();
//                Log.d("MainActivity", "onError: " + error.getMessage());
            }
        });
    }


数据回调

  @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO) {
            if (resultCode == RESULT_OK) {
                beginCrop(imageUri, from);
            }
        }
        if (requestCode == CHOOSE_PHOTO) {
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKatKit(data);
                } else {
                    handleImageBeforKatKit(data);
                }
            }
        }
        if (requestCode == Crop.REQUEST_PICK) {
            if (resultCode == RESULT_OK) {
                beginCrop(data.getData(), from);
            }
        }
        if (requestCode == Crop.REQUEST_CROP) {
            handleCrop(resultCode, data);
        }
        // 识别成功回调,网络图片文字识别
        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);

        }

//        if (requestCode == REQUEST_CODE_PICK_IMAGE_BACK && resultCode == Activity.RESULT_OK) {
//            Uri uri = data.getData();
//            String filePath = getRealPathFromURI(uri);
//            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
//        }
//        if (requestCode == REQUEST_CODE_GENERAL_WEBIMAGE && resultCode == Activity.RESULT_OK) {
//            RecognizeService.recWebimage(this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(), new
//                    RecognizeService.ServiceListener() {
//                        @Override
//                        public void onResult(String result) {
//                            infoPopText(result);
//                        }
//                    });
//
//        }
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                RecognizeService.recBankCard(this, FileUtil.getSaveFile(getApplicationContext(),3).getAbsolutePath(),
                        new RecognizeService.ServiceListener() {
                            @Override
                            public void onResult(String result) {
                                recCreditCard(FileUtil.getSaveFile(getApplicationContext(),3).getAbsolutePath());
                            }
                        });
            }
        }
            if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);


                    if (!TextUtils.isEmpty(contentType)) {
                        if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                            String filePath1 = FileUtil.getSaveFile(getApplicationContext(),1).getAbsolutePath();
                            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath1);
//                            zhengmianFile = new File(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
//                            Log.i("身份证",filePath+"文件"+zhengmianFile);
                        } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                            String filePath2 = FileUtil.getSaveFile(getApplicationContext(),2).getAbsolutePath();
                            recIDCard1(IDCardParams.ID_CARD_SIDE_BACK, filePath2);
//                             fanmianFile = new File(IDCardParams.ID_CARD_SIDE_BACK, filePath);
//                            Log.i("身份证",filePath+"文件"+zhengmianFile);
                        }
                    }
            }
        }
if (requestCode == REQUEST_CODE_LICENSE_PLATE && resultCode == Activity.RESULT_OK) { RecognizeService.recLicensePlate(getActivity(), FileUtil.getSaveFile(mActivity.getApplicationContext()).getAbsolutePath(),new RecognizeService.ServiceListener() {
@Override
 public void onResult(String result) {
 String filePath1 = FileUtil.getSaveFile(getActivity().getApplicationContext()).getAbsolutePath();
chepai(1,filePath1);
 }
});
 }
 

你可能感兴趣的:(基于百度ai实现身份证,银行卡自动识别,车牌识别)