如何在Android Studio中使用Amazon Rekognition实现图片物体检测
Android Studio调用Amazon Rekognition物体检测实现方案
前置准备
你需要先完成AWS账号基础配置:开通Amazon Rekognition服务,创建具备rekognition:DetectLabels调用权限的IAM用户,拿到对应的AccessKey、SecretKey。注意:测试阶段可临时使用固定密钥,生产环境绝对不要把密钥硬编码在APK包中,建议配合AWS Cognito发放临时访问凭证避免密钥泄露
第一步:项目依赖配置
在项目根目录的build.gradle(Project层级)的repositories块中添加AWS Maven源:
maven { url 'https://aws.amazon.com/maven2/' }
在模块级的build.gradle(Module层级)的dependencies块中引入依赖,版本号可根据实际情况调整:
dependencies { implementation 'com.amazonaws:aws-android-sdk-rekognition:2.70.0' implementation 'com.amazonaws:aws-android-sdk-core:2.70.0' }
配置完成后同步Gradle即可。
第二步:权限配置
在AndroidManifest.xml中添加网络权限,Rekognition接口调用需要联网:
<uses-permission android:name="android.permission.INTERNET" />
第三步:核心检测功能实现
封装工具类实现图片检测逻辑,注意:网络请求必须在子线程执行,不要直接在主线程调用:
import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.rekognition.AmazonRekognitionClient; import com.amazonaws.services.rekognition.model.*; import android.graphics.Bitmap; import android.util.Log; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.List; public class RekognitionHelper { // 测试用密钥,生产环境请删除,改为从Cognito获取临时凭证 private static final String ACCESS_KEY = "替换为你的IAM用户AccessKey"; private static final String SECRET_KEY = "替换为你的IAM用户SecretKey"; private static final String SERVICE_REGION = "us-east-1"; // 替换为你开通服务的区域 public static void detectImageObjects(Bitmap imageBitmap, DetectResultListener listener) { new Thread(() -> { try { // 初始化Rekognition客户端 BasicAWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY); AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(credentials); rekognitionClient.setRegion(com.amazonaws.regions.Region.getRegion(SERVICE_REGION)); // 将Bitmap转换为接口要求的字节流格式 ByteArrayOutputStream stream = new ByteArrayOutputStream(); imageBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream); ByteBuffer imageBytes = ByteBuffer.wrap(stream.toByteArray()); // 构造检测请求,可自行调整返回标签数量和置信度阈值 DetectLabelsRequest request = new DetectLabelsRequest() .withImage(new Image().withBytes(imageBytes)) .withMaxLabels(10) .withMinConfidence(75F); // 发起请求获取结果 DetectLabelsResult result = rekognitionClient.detectLabels(request); List<Label> detectLabels = result.getLabels(); if (listener != null) listener.onSuccess(detectLabels); } catch (Exception e) { Log.e("Rekognition检测", "调用失败", e); if (listener != null) listener.onError(e.getMessage()); } }).start(); } // 结果回调接口 public interface DetectResultListener { void onSuccess(List<Label> labels); void onError(String errorMsg); } }
第四步:功能调用示例
在Activity中拿到选中/拍摄的图片Bitmap后,直接调用工具类即可,结果回调后切回主线程更新UI:
// 此处selectedImageBitmap为你获取到的待检测图片Bitmap对象 RekognitionHelper.detectImageObjects(selectedImageBitmap, new RekognitionHelper.DetectResultListener() { @Override public void onSuccess(List<Label> labels) { runOnUiThread(() -> { // 遍历结果更新UI即可 for (Label label : labels) { Log.d("检测结果", "物体名称:" + label.getName() + ",置信度:" + label.getConfidence() + "%"); } }); } @Override public void onError(String errorMsg) { runOnUiThread(() -> { // 处理错误逻辑 Log.e("检测失败", errorMsg); }); } });
注意事项
- Rekognition支持的图片格式为JPEG、PNG,单张图片大小不能超过15MB
- 调用前请确认你的IAM用户已经配置了足够的Rekognition服务权限
- 生产环境请务必替换硬编码的密钥方案,避免账号安全风险
内容的提问来源于stack exchange,提问作者Rob Aberan
相关产品推荐
相关产品推荐

