SDK for Kotlin を使用する Amazon Rekognition の例 - AWS SDK コード例

Doc AWS SDK Examples GitHub リポジトリには、他にも SDK の例があります。 AWS

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

SDK for Kotlin を使用する Amazon Rekognition の例

次のコード例は、Amazon Rekognition で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。 Amazon Rekognition

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

「シナリオ」は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコンテキストにおけるコードの設定方法と実行方法についての手順を確認できます。

アクション

次のコード例は、CompareFaces を使用する方法を示しています。

詳細については、「イメージ内の顔を比較する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「CompareFaces」を参照してください。

次の例は、CreateCollection を使用する方法を説明しています。

詳細については、「コレクションを作成する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「CreateCollection」を参照してください。

次の例は、DeleteCollection を使用する方法を説明しています。

詳細については、「コレクションを削除する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「DeleteCollection」を参照してください。

次の例は、DeleteFaces を使用する方法を説明しています。

詳細については、「コレクションから顔を削除する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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") } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「DeleteFaces」を参照してください。

次のコード例は、DescribeCollection を使用する方法を示しています。

詳細については、「コレクションを定義する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「DescribeCollection」を参照してください。

次のコード例は、DetectFaces を使用する方法を示しています。

詳細については、「イメージ内の顔を検出する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「DetectFaces」を参照してください。

次のコード例は、DetectLabels を使用する方法を示しています。

詳細については、「イメージ内のラベルを検出する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「DetectLabels」を参照してください。

次のコード例は、DetectModerationLabels を使用する方法を示しています。

詳細については、「不適切なイメージを検出する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「DetectModerationLabels」を参照してください。

次の例は、DetectText を使用する方法を説明しています。

詳細については、「イメージ内のテキストを検出する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「DetectText」を参照してください。

次の例は、IndexFaces を使用する方法を説明しています。

詳細については、「コレクションに顔を追加する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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") } } } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「IndexFaces」を参照してください。

次の例は、ListCollections を使用する方法を説明しています。

コレクションの詳細については、「コレクションを一覧表示する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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) } } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「ListCollections」を参照してください。

次の例は、ListFaces を使用する方法を説明しています。

詳細については、「コレクションに顔を保存する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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}") } } }
  • API の詳細については、「AWS SDK for Kotlin API Reference」の「ListFaces」を参照してください。

次のコード例は、RecognizeCelebrities を使用する方法を示しています。

詳細については、「イメージ内で有名人を認識する」を参照してください。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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.") } }
  • API の詳細については、AWS SDK for Kotlin API リファレンスの「RecognizeCelebrities」を参照してください。

シナリオ

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

SDK for Kotlin

Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。

完全なソースコードと設定および実行の手順については、GitHub で完全な例を参照してください。

この例のソースについて詳しくは、AWS  コミュニティでブログ投稿を参照してください。

この例で使用されているサービス
  • API Gateway

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

次のコードサンプルは、以下の操作方法を示しています。

  • Amazon Rekognition のジョブを開始し、人物、オブジェクト、テキストなどの要素を動画から検出します。

  • ジョブが完了するまでジョブのステータスを確認します。

  • 検出された要素のリストをジョブごとに出力します。

SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

Amazon S3 バケットに保存されたビデオ内の顔を検出する

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}") } } }

Amazon S3 バケットに保存されたビデオ内の不適切なコンテンツや攻撃的なコンテンツを検出します。

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) } } }

次のコード例は、Amazon Rekognition を使用してイメージ内のオブジェクトをカテゴリ別に検出するアプリを構築する方法を示しています。

SDK for Kotlin

Amazon Simple Storage Service (Amazon S3) バケットにある画像内からカテゴリ別にオブジェクトを Amazon Rekognition を使用して識別するアプリケーションを、Amazon Rekognition Kotlin API を使用して作成する方法を示します。アプリケーションは、Amazon Simple Email Service (Amazon SES) を使用して、結果を記載した E メール通知を管理者に送信します。

完全なソースコードとセットアップおよび実行の手順については、GitHub で完全な例を参照してください。

この例で使用されているサービス
  • Amazon Rekognition

  • Amazon S3

  • Amazon SES