Android端AWS Rekognition服务CompareFacesRequest调用报错求助
Hey there! No worries at all about being new to posting—we’ve all fumbled through our first tech questions, so awkward wording is totally fine. Let’s fix up your face matching problem with AWS Rekognition in your Android app, since it looks like your code snippet cuts off right when you need the core logic.
First: Complete Your Rekognition Client Setup
You got the credentials provider right, but the client initialization was incomplete. Also, quick heads-up: the old AmazonRekognitionClient is legacy—if you’re starting fresh, the newer AWS SDK v2 is better supported. I’ll cover both options below.
Legacy SDK v1 Example
// Your existing credentials setup (keep this!) CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider( getApplicationContext(), "YOUR_IDENTITY_POOL_ID", // Replace with your actual pool ID Regions.US_EAST_1 ); // Finish initializing the Rekognition client AmazonRekognition rekognitionClient = new AmazonRekognitionClient(credentialsProvider); rekognitionClient.setRegion(Region.getRegion(Regions.US_EAST_1));
Recommended SDK v2 Example
This is the modern, maintained version—worth switching to if you can:
// Initialize credentials for v2 AwsCredentialsProvider credentialsProvider = CognitoCredentialsProvider.create( "YOUR_IDENTITY_POOL_ID", Regions.US_EAST_1.id() ); // Build the Rekognition client RekognitionClient rekognitionClient = RekognitionClient.builder() .credentialsProvider(credentialsProvider) .region(Region.of(Regions.US_EAST_1.id())) .build();
Second: Add the Face Matching Logic
The big missing piece is creating and sending the CompareFacesRequest with your two images. You’ll need to convert your Android Bitmap (or image file) into a ByteBuffer that AWS can process.
SDK v1 Face Matching Implementation
// Helper to turn a Bitmap into a ByteBuffer for AWS private ByteBuffer convertBitmapToByteBuffer(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); return ByteBuffer.wrap(stream.toByteArray()); } // Main method to run the face match public void compareFaces(Bitmap sourcePic, Bitmap targetPic) { // Prepare both images for the request Image sourceImage = new Image().withBytes(convertBitmapToByteBuffer(sourcePic)); Image targetImage = new Image().withBytes(convertBitmapToByteBuffer(targetPic)); // Build the request (adjust similarity threshold as needed) CompareFacesRequest request = new CompareFacesRequest() .withSourceImage(sourceImage) .withTargetImage(targetImage) .withSimilarityThreshold(70F); // Run the request on a background thread (never main thread!) new AsyncTask<Void, Void, CompareFacesResult>() { @Override protected CompareFacesResult doInBackground(Void... voids) { try { return rekognitionClient.compareFaces(request); } catch (AmazonServiceException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(CompareFacesResult result) { if (result != null) { List<CompareFacesMatch> matches = result.getFaceMatches(); if (!matches.isEmpty()) { float similarity = matches.get(0).getSimilarity(); Log.d("FaceMatch", "Match found! Similarity: " + similarity + "%"); // Update your UI with this result here } else { Log.d("FaceMatch", "No matching faces found."); } } else { Log.e("FaceMatch", "Request failed—check your setup!"); } } }.execute(); }
SDK v2 Face Matching Implementation
// Same helper method for Bitmap to ByteBuffer as above public void compareFacesV2(Bitmap sourcePic, Bitmap targetPic) { // Prepare images for v2 SDK Software.amazon.awssdk.services.rekognition.model.Image sourceImage = Software.amazon.awssdk.services.rekognition.model.Image.builder() .bytes(convertBitmapToByteBuffer(sourcePic)) .build(); Software.amazon.awssdk.services.rekognition.model.Image targetImage = Software.amazon.awssdk.services.rekognition.model.Image.builder() .bytes(convertBitmapToByteBuffer(targetPic)) .build(); // Build the request CompareFacesRequest request = CompareFacesRequest.builder() .sourceImage(sourceImage) .targetImage(targetImage) .similarityThreshold(70F) .build(); // Run on a background thread (v2 works great with threads/coroutines) new Thread(() -> { try { CompareFacesResponse response = rekognitionClient.compareFaces(request); // Post results back to main thread for UI updates runOnUiThread(() -> { List<CompareFacesMatch> matches = response.faceMatches(); if (!matches.isEmpty()) { float similarity = matches.get(0).similarity().floatValue(); Log.d("FaceMatchV2", "Match found! Similarity: " + similarity + "%"); } else { Log.d("FaceMatchV2", "No matching faces found."); } }); } catch (RekognitionException e) { e.printStackTrace(); runOnUiThread(() -> Log.e("FaceMatchV2", "Error: " + e.getMessage())); } }).start(); }
Common Pitfalls to Check
- IAM Permissions: Make sure your Cognito Identity Pool’s IAM role has the
rekognition:CompareFacespermission—without this, AWS will reject your request. - Image Format: Rekognition only supports JPEG, PNG, and BMP—double-check your images are in one of these formats.
- Main Thread Rule: Always run AWS SDK calls on a background thread (like we did with AsyncTask/Thread) to avoid app crashes from ANRs.
- Region Mismatch: Ensure your client’s region matches the one where your Identity Pool was created.
Give this a shot, and if you hit specific errors (like permission denied or image processing issues), just share the details and we’ll troubleshoot further!
内容的提问来源于stack exchange,提问作者Dhruv Khurana

