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

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

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

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

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

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

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

アクション

次のコード例は、Amazon Rekognition でイメージ内の顔とリファレンスイメージを比較する方法を示しています。

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

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

次のコード例は、Amazon Rekognition コレクションを作成する方法を示しています。

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

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

次のコード例は、Amazon Rekognition コレクションを削除する方法を示します。

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

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

次のコード例は、Amazon Rekognition コレクションから顔を削除する方法を示します。

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

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

次のコード例は、Amazon Rekognition コレクションを記述する方法を示しています。

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

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

次のコード例は、Amazon Rekognition でイメージ内の顔を検出する方法を示します。

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

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

次のコード例は、Amazon Rekognition でイメージ内のラベルを検出する方法を示します。

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

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

以下のコード例は、Amazon Rekognition でイメージ内でモデレーションラベルを検出する方法を示しています。モデレーションラベルは、一部のオーディエンスにとって不適切なコンテンツを識別します。

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

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

次のコード例は、Amazon Rekognition でイメージ内のテキストを検出する方法を示します。

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

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

以下のコード例は、イメージで顔のインデックスを作成し Amazon Rekognition コレクションに追加する方法を示しています。

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

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

次のコード例は、Amazon Rekognition のコレクションの一覧表示方法を示しています。

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

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

次のコード例は、Amazon Rekognition コレクション内の顔を一覧表示する方法を示します。

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

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

次のコード例は、Amazon Rekognition を使用して、イメージ内の有名人を認識する方法を示します。

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

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

シナリオ

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

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