Amazon Rekognition examples using SDK for Kotlin - AWS SDK for Kotlin

Amazon Rekognition examples using SDK for Kotlin

The following code examples show you how to perform actions and implement common scenarios by using the AWS SDK for Kotlin with Amazon Rekognition.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Actions

The following code example shows how to use CompareFaces.

For more information, see Comparing faces in images.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun compareTwoFaces(similarityThresholdVal: Float, sourceImageVal: String, targetImageVal: String) { val sourceBytes = (File(sourceImageVal).readBytes()) val targetBytes = (File(targetImageVal).readBytes()) // Create an Image object for the source image. val souImage = Image { bytes = sourceBytes } val tarImage = Image { bytes = targetBytes } val facesRequest = CompareFacesRequest { sourceImage = souImage targetImage = tarImage similarityThreshold = similarityThresholdVal } RekognitionClient { region = "us-east-1" }.use { rekClient -> val compareFacesResult = rekClient.compareFaces(facesRequest) val faceDetails = compareFacesResult.faceMatches if (faceDetails != null) { for (match: CompareFacesMatch in faceDetails) { val face = match.face val position = face?.boundingBox if (position != null) println("Face at ${position.left} ${position.top} matches with ${face.confidence} % confidence.") } } val uncompared = compareFacesResult.unmatchedFaces if (uncompared != null) println("There was ${uncompared.size} face(s) that did not match") println("Source image rotation: ${compareFacesResult.sourceImageOrientationCorrection}") println("target image rotation: ${compareFacesResult.targetImageOrientationCorrection}") } }
  • For API details, see CompareFaces in AWS SDK for Kotlin API reference.

The following code example shows how to use CreateCollection.

For more information, see Creating a collection.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun createMyCollection(collectionIdVal: String) { val request = CreateCollectionRequest { collectionId = collectionIdVal } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.createCollection(request) println("Collection ARN is ${response.collectionArn}") println("Status code is ${response.statusCode}") } }

The following code example shows how to use DeleteCollection.

For more information, see Deleting a collection.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun deleteMyCollection(collectionIdVal: String) { val request = DeleteCollectionRequest { collectionId = collectionIdVal } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.deleteCollection(request) println("The collectionId status is ${response.statusCode}") } }

The following code example shows how to use DeleteFaces.

For more information, see Deleting faces from a collection.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun deleteFacesCollection(collectionIdVal: String?, faceIdVal: String) { val deleteFacesRequest = DeleteFacesRequest { collectionId = collectionIdVal faceIds = listOf(faceIdVal) } RekognitionClient { region = "us-east-1" }.use { rekClient -> rekClient.deleteFaces(deleteFacesRequest) println("$faceIdVal was deleted from the collection") } }
  • For API details, see DeleteFaces in AWS SDK for Kotlin API reference.

The following code example shows how to use DescribeCollection.

For more information, see Describing a collection.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun describeColl(collectionName: String) { val request = DescribeCollectionRequest { collectionId = collectionName } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.describeCollection(request) println("The collection Arn is ${response.collectionArn}") println("The collection contains this many faces ${response.faceCount}") } }

The following code example shows how to use DetectFaces.

For more information, see Detecting faces in an image.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun detectFacesinImage(sourceImage: String?) { val souImage = Image { bytes = (File(sourceImage).readBytes()) } val request = DetectFacesRequest { attributes = listOf(Attribute.All) image = souImage } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.detectFaces(request) response.faceDetails?.forEach { face -> val ageRange = face.ageRange println("The detected face is estimated to be between ${ageRange?.low} and ${ageRange?.high} years old.") println("There is a smile ${face.smile?.value}") } } }
  • For API details, see DetectFaces in AWS SDK for Kotlin API reference.

The following code example shows how to use DetectLabels.

For more information, see Detecting labels in an image.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun detectImageLabels(sourceImage: String) { val souImage = Image { bytes = (File(sourceImage).readBytes()) } val request = DetectLabelsRequest { image = souImage maxLabels = 10 } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.detectLabels(request) response.labels?.forEach { label -> println("${label.name} : ${label.confidence}") } } }
  • For API details, see DetectLabels in AWS SDK for Kotlin API reference.

The following code example shows how to use DetectModerationLabels.

For more information, see Detecting inappropriate images.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun detectModLabels(sourceImage: String) { val myImage = Image { this.bytes = (File(sourceImage).readBytes()) } val request = DetectModerationLabelsRequest { image = myImage minConfidence = 60f } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.detectModerationLabels(request) response.moderationLabels?.forEach { label -> println("Label: ${label.name} - Confidence: ${label.confidence} % Parent: ${label.parentName}") } } }

The following code example shows how to use DetectText.

For more information, see Detecting text in an image.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun detectTextLabels(sourceImage: String?) { val souImage = Image { bytes = (File(sourceImage).readBytes()) } val request = DetectTextRequest { image = souImage } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.detectText(request) response.textDetections?.forEach { text -> println("Detected: ${text.detectedText}") println("Confidence: ${text.confidence}") println("Id: ${text.id}") println("Parent Id: ${text.parentId}") println("Type: ${text.type}") } } }
  • For API details, see DetectText in AWS SDK for Kotlin API reference.

The following code example shows how to use IndexFaces.

For more information, see Adding faces to a collection.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun addToCollection(collectionIdVal: String?, sourceImage: String) { val souImage = Image { bytes = (File(sourceImage).readBytes()) } val request = IndexFacesRequest { collectionId = collectionIdVal image = souImage maxFaces = 1 qualityFilter = QualityFilter.Auto detectionAttributes = listOf(Attribute.Default) } RekognitionClient { region = "us-east-1" }.use { rekClient -> val facesResponse = rekClient.indexFaces(request) // Display the results. println("Results for the image") println("\n Faces indexed:") facesResponse.faceRecords?.forEach { faceRecord -> println("Face ID: ${faceRecord.face?.faceId}") println("Location: ${faceRecord.faceDetail?.boundingBox}") } println("Faces not indexed:") facesResponse.unindexedFaces?.forEach { unindexedFace -> println("Location: ${unindexedFace.faceDetail?.boundingBox}") println("Reasons:") unindexedFace.reasons?.forEach { reason -> println("Reason: $reason") } } } }
  • For API details, see IndexFaces in AWS SDK for Kotlin API reference.

The following code example shows how to use ListCollections.

For more information, see Listing collections.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun listAllCollections() { val request = ListCollectionsRequest { maxResults = 10 } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.listCollections(request) response.collectionIds?.forEach { resultId -> println(resultId) } } }
  • For API details, see ListCollections in AWS SDK for Kotlin API reference.

The following code example shows how to use ListFaces.

For more information, see Listing faces in a collection.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun listFacesCollection(collectionIdVal: String?) { val request = ListFacesRequest { collectionId = collectionIdVal maxResults = 10 } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.listFaces(request) response.faces?.forEach { face -> println("Confidence level there is a face: ${face.confidence}") println("The face Id value is ${face.faceId}") } } }
  • For API details, see ListFaces in AWS SDK for Kotlin API reference.

The following code example shows how to use RecognizeCelebrities.

For more information, see Recognizing celebrities in an image.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun recognizeAllCelebrities(sourceImage: String?) { val souImage = Image { bytes = (File(sourceImage).readBytes()) } val request = RecognizeCelebritiesRequest { image = souImage } RekognitionClient { region = "us-east-1" }.use { rekClient -> val response = rekClient.recognizeCelebrities(request) response.celebrityFaces?.forEach { celebrity -> println("Celebrity recognized: ${celebrity.name}") println("Celebrity ID:${celebrity.id}") println("Further information (if available):") celebrity.urls?.forEach { url -> println(url) } } println("${response.unrecognizedFaces?.size} face(s) were unrecognized.") } }

Scenarios

The following code example shows how to:

  • Start Amazon Rekognition jobs to detect elements like people, objects, and text in videos.

  • Check job status until jobs finish.

  • Output the list of elements detected by each job.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

Detect faces in a video stored in an Amazon S3 bucket.

suspend fun startFaceDetection(channelVal: NotificationChannel?, bucketVal: String, videoVal: String) { val s3Obj = S3Object { bucket = bucketVal name = videoVal } val vidOb = Video { s3Object = s3Obj } val request = StartFaceDetectionRequest { jobTag = "Faces" faceAttributes = FaceAttributes.All notificationChannel = channelVal video = vidOb } RekognitionClient { region = "us-east-1" }.use { rekClient -> val startLabelDetectionResult = rekClient.startFaceDetection(request) startJobId = startLabelDetectionResult.jobId.toString() } } suspend fun getFaceResults() { var finished = false var status: String var yy = 0 RekognitionClient { region = "us-east-1" }.use { rekClient -> var response: GetFaceDetectionResponse? = null val recognitionRequest = GetFaceDetectionRequest { jobId = startJobId maxResults = 10 } // Wait until the job succeeds. while (!finished) { response = rekClient.getFaceDetection(recognitionRequest) status = response.jobStatus.toString() if (status.compareTo("SUCCEEDED") == 0) finished = true else { println("$yy status is: $status") delay(1000) } yy++ } // Proceed when the job is done - otherwise VideoMetadata is null. val videoMetaData = response?.videoMetadata println("Format: ${videoMetaData?.format}") println("Codec: ${videoMetaData?.codec}") println("Duration: ${videoMetaData?.durationMillis}") println("FrameRate: ${videoMetaData?.frameRate}") // Show face information. response?.faces?.forEach { face -> println("Age: ${face.face?.ageRange}") println("Face: ${face.face?.beard}") println("Eye glasses: ${face?.face?.eyeglasses}") println("Mustache: ${face.face?.mustache}") println("Smile: ${face.face?.smile}") } } }

Detect inappropriate or offensive content in a video stored in an Amazon S3 bucket.

suspend fun startModerationDetection(channel: NotificationChannel?, bucketVal: String?, videoVal: String?) { val s3Obj = S3Object { bucket = bucketVal name = videoVal } val vidOb = Video { s3Object = s3Obj } val request = StartContentModerationRequest { jobTag = "Moderation" notificationChannel = channel video = vidOb } RekognitionClient { region = "us-east-1" }.use { rekClient -> val startModDetectionResult = rekClient.startContentModeration(request) startJobId = startModDetectionResult.jobId.toString() } } suspend fun getModResults() { var finished = false var status: String var yy = 0 RekognitionClient { region = "us-east-1" }.use { rekClient -> var modDetectionResponse: GetContentModerationResponse? = null val modRequest = GetContentModerationRequest { jobId = startJobId maxResults = 10 } // Wait until the job succeeds. while (!finished) { modDetectionResponse = rekClient.getContentModeration(modRequest) status = modDetectionResponse.jobStatus.toString() if (status.compareTo("SUCCEEDED") == 0) finished = true else { println("$yy status is: $status") delay(1000) } yy++ } // Proceed when the job is done - otherwise VideoMetadata is null. val videoMetaData = modDetectionResponse?.videoMetadata println("Format: ${videoMetaData?.format}") println("Codec: ${videoMetaData?.codec}") println("Duration: ${videoMetaData?.durationMillis}") println("FrameRate: ${videoMetaData?.frameRate}") modDetectionResponse?.moderationLabels?.forEach { mod -> val seconds: Long = mod.timestamp / 1000 print("Mod label: $seconds ") println(mod.moderationLabel) } } }