Giter Club home page Giter Club logo

amazon-rekognition-developer-guide's Introduction

Amazon Rekognition Developer Guide

The open source version of the Amazon Rekognition docs. You can submit feedback & requests for changes by submitting issues in this repo or by making proposed changes & submitting a pull request.

License Summary

The documentation is made available under the Creative Commons Attribution-ShareAlike 4.0 International License. See the LICENSE file.

The sample code within this documentation is made available under a modified MIT license. See the LICENSE-SAMPLECODE file.

amazon-rekognition-developer-guide's People

Contributors

ahmadmustafaanis avatar aldy120 avatar anuj-patel avatar awschris avatar cesarkohl avatar dnelsamz avatar ettienek2 avatar hemantpande avatar ianwow avatar joshbean avatar jpeddicord avatar limpingninja avatar luiscosio avatar nijerica avatar ojkelly avatar omenking avatar paulomigalmeida avatar qbicz avatar shirkeyaws avatar titanium-cranium avatar zachlatta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

amazon-rekognition-developer-guide's Issues

Parameter validation failed:\nUnknown parameter in input: \"Features\"

Unable to get image properties using python 9

import json
import boto3
def lambda_handler(event, context):
fileName='7up_Free.jpg'
bucket='image-auditing-bucket'

client=boto3.client('rekognition')

#response = client.detect_labels(Image={'S3Object':{'Bucket':bucket,'Name':fileName}},MaxLabels=3,  MinConfidence=70,'Features':['GENERAL_LABELS'])

response = client.detect_labels(
Image={
    'S3Object': {
        'Bucket': bucket,
        'Name': fileName
    }
},
MaxLabels=123,
MinConfidence=50,
Features=[
    'GENERAL_LABELS','IMAGE_PROPERTIES',
],
Settings={
    'ImageProperties': {
        'MaxDominantColors': 123
    }
}

)

print('Detected labels for ' + fileName)    
for label in response['Labels']:
    print (label['Name'] + ' : ' + str(label['Confidence']))

Getting error

Test Event Name
test

Response
{
"errorMessage": "Parameter validation failed:\nUnknown parameter in input: "Features", must be one of: Image, MaxLabels, MinConfidence\nUnknown parameter in input: "Settings", must be one of: Image, MaxLabels, MinConfidence",
"errorType": "ParamValidationError",
"requestId": "2f6b2ba3-79c3-4656-b2e8-0149955b9884",
"stackTrace": [
" File "/var/task/lambda_function.py", line 11, in lambda_handler\n response = client.detect_labels(\n",
" File "/var/runtime/botocore/client.py", line 391, in _api_call\n return self._make_api_call(operation_name, kwargs)\n",
" File "/var/runtime/botocore/client.py", line 691, in _make_api_call\n request_dict = self._convert_to_request_dict(\n",
" File "/var/runtime/botocore/client.py", line 739, in _convert_to_request_dict\n request_dict = self._serializer.serialize_to_request(\n",
" File "/var/runtime/botocore/validate.py", line 360, in serialize_to_request\n raise ParamValidationError(report=report.generate_report())\n"
]
}

Function Logs
START RequestId: 2f6b2ba3-79c3-4656-b2e8-0149955b9884 Version: $LATEST
[ERROR] ParamValidationError: Parameter validation failed:
Unknown parameter in input: "Features", must be one of: Image, MaxLabels, MinConfidence
Unknown parameter in input: "Settings", must be one of: Image, MaxLabels, MinConfidence
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 11, in lambda_handler
    response = client.detect_labels(
  File "/var/runtime/botocore/client.py", line 391, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/runtime/botocore/client.py", line 691, in _make_api_call
    request_dict = self._convert_to_request_dict(
  File "/var/runtime/botocore/client.py", line 739, in _convert_to_request_dict
    request_dict = self._serializer.serialize_to_request(
  File "/var/runtime/botocore/validate.py", line 360, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())END RequestId: 2f6b2ba3-79c3-4656-b2e8-0149955b9884
REPORT RequestId: 2f6b2ba3-79c3-4656-b2e8-0149955b9884 Duration: 867.77 ms Billed Duration: 868 ms Memory Size: 128 MB Max Memory Used: 64 MB Init Duration: 229.89 ms

Request ID
2f6b2ba3-79c3-4656-b2e8-0149955b9884

Golang example to read local image and Detect labels

There is no Golang sample code available for detecting labels in Analyzing an image loaded from a local file system :
https://docs.aws.amazon.com/rekognition/latest/dg/images-bytes.html

My Golang snippet works fine and Produces the desired Result:

package main

import (
	"fmt"
	"os"
	"bufio"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/rekognition"
)

var svc *rekognition.Rekognition

func init() {

  	sess, err := session.NewSession(&aws.Config{
  		Region: aws.String("us-east-1"),
  	})

  	if err != nil {
  		fmt.Println("Error while creating session,", err)
  		return
  	}

  	svc = rekognition.New(sess)
  	_ = svc
}

func main() {

  	//local image file
  	imageFile := "/your/path/to/image.jpg"

  	file, err := os.Open(imageFile)
  	if err != nil {
  		fmt.Println(err)
  		return
  	}

  	defer file.Close()

  	fileInfo, _ := file.Stat()
  	var size int64 = fileInfo.Size()
  	bytes := make([]byte, size)

  	// read file into bytes
  	buffer := bufio.NewReader(file)

  	//write into bytes
  	_, err = buffer.Read(bytes)   

  	//Prepare image data for Rekognition
  	input := &rekognition.DetectLabelsInput{
  		Image: &rekognition.Image{
  			Bytes: bytes,
  		},
  	}

  	//Detect Lables
  	resp, err := svc.DetectLabels(input)

  	if err != nil { //If there is an Error
  		fmt.Println(err.Error())
  		return
  	}

  	fmt.Printf("\nDetected Labels for %s\n", imageFile)

  	for _, label := range resp.Labels {

  		fmt.Printf("\nLabel : %v\n", *label.Name)
  		fmt.Printf("Confidence : %v\n", *label.Confidence)


  	}

  	fmt.Printf("\nLabels Detected : %d\n", len(resp.Labels))

}

labels

Submitting a Pull Request with the above changes.

Java Json (Jackson) Serialization broken/howto?

i follow this guide:
https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/doc_source/faces-detect-images.md

and that line:
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(face));
is throwing exception:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class software.amazon.awssdk.services.rekognition.model.FaceDetail and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

I am using latest rekognition java sdk: 2.16.58
Probably this guide is for older sdk, but i can't find any v2 variant or something.
Please update guide how to get json with the current java sdk.

Golang example for detecting faces in Image

No Golang code sample available for detecting faces in Images in the Developer Guide:

https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html

My Golang code snippet works fine for the example.

package main

    import (
        "fmt"

        "github.com/aws/aws-sdk-go/aws"
        "github.com/aws/aws-sdk-go/aws/session"
        "github.com/aws/aws-sdk-go/service/rekognition"
    )

    var svc *rekognition.Rekognition

    func init() {

        //https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/sessions.html

        //Access keys are read from ~/.aws/credentials
        sess, err := session.NewSession(&aws.Config{
            Region: aws.String("us-east-1"),
        })

        if err != nil {
            fmt.Println("Error while creating session,", err)
            return
        }

        svc = rekognition.New(sess)
        _ = svc
    }

    func main() {

        bucket := "" //Bucket name from S3
        photo := ""  //Image File

        params := &rekognition.DetectFacesInput{
            Image: &rekognition.Image{ // Required

                S3Object: &rekognition.S3Object{
                    Bucket: aws.String(bucket),
                    Name:   aws.String(photo),
                },
            },
            Attributes: []*string{
                aws.String("ALL"), // Required
            },
        }

        resp, err := svc.DetectFaces(params)

        if err != nil { //If there is an Error
            fmt.Println(err.Error())
            return
        }

        for idx, fdetails := range resp.FaceDetails {

            fmt.Printf("Person #%d : \n", idx+1)
            fmt.Printf("Position : %v %v \n", *fdetails.BoundingBox.Left, *fdetails.BoundingBox.Top)

            if fdetails.AgeRange != nil {
                fmt.Printf("Age (Low) : %d \n", *fdetails.AgeRange.Low)
                fmt.Printf("Age (High) : %d \n", *fdetails.AgeRange.High)
            }

            if fdetails.Emotions != nil {
                fmt.Printf("Emotion : %v\n", *fdetails.Emotions[0].Type)
            }

            if fdetails.Gender != nil {
                fmt.Printf("Gender : %v\n\n", *fdetails.Gender.Value)
            }
        }

    }

produces desired result :

go-face-detect

Creating a Pull request with the above changes.

infin loop

i used the same code but the result shown to infinite loop (.) waiting for result

Waiting for job: c6798
false
....................
....................
....................
....................
....................
....................
....................
....................
....................

Error AccessDenied

Hello, I have been trying to create a stream processor using python on my Raspberry Pi. Below is the error I got:

Traceback (most recent call last): File "/home/pi/Codes/AWS-Services/creating-stream-processor.py", line 34, in <module> main() File "/home/pi/Codes/AWS-Services/creating-stream-processor.py", line 32, in main create_stream_processor() File "/home/pi/Codes/AWS-Services/creating-stream-processor.py", line 26, in create_stream_processor 'Arn': 'arn:aws:kinesis:ap-southeast-1:121234567890:stream/DataStream-bmebpd' File "/home/pi/.local/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/pi/.local/lib/python3.7/site-packages/botocore/client.py", line 676, in _make_api_call raise error_class(parsed_response, operation_name) **botocore.errorfactory.AccessDeniedException: An error occurred (AccessDeniedException) when calling the CreateStreamProcessor operation: **

Below is mycode for creating a stream processor for python:
'import boto3

def create_stream_processor():

client = boto3.client('rekognition')
    
response = client.create_stream_processor(
    Name='streamprocessor-bmebpd',
    RoleArn= 'arn:aws:iam::121234567890:role/Rekognition-bmebpd',
    Settings={
        'FaceSearch': {
            'FaceMatchThreshold': 80.0,
            'CollectionId': 'collection'
        }
    },
    Input={
        'KinesisVideoStream': {
            'Arn': 'arn:aws:kinesisvideo:ap-southeast-121234567890:stream/VideoStream/1234567890'
        }
    },
    Output={
        'KinesisDataStream': {
            'Arn': 'arn:aws:kinesis:us-east-1:121234567890:stream/DataStream'
        }
    }
)

def main():
create_stream_processor()
if name == "main":
main() '

I have given my roles FullAccess.

NodeJs example for Detecting Labels in an Image

Since I just created a Ruby example I would be remiss to not create one for NodeJS 10.x

Screen Shot 2019-07-26 at 3 51 23 PM

// Add to your package.json
// npm install aws-sdk --save-dev

const AWS = require('aws-sdk')

const bucket = 'mybucket' // the bucketname without s3://
const photo  = 'photo.png' // the name of file

const config = new AWS.Config({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: process.env.AWS_REGION
})

const client = new AWS.Rekognition();
const params = {
  Image: {
    S3Object: {
      Bucket: bucket,
      Name: photo
    },
  },
  MaxLabels: 10
}
client.detectLabels(params, function(err, response) {
  if (err) {
    console.log(err, err.stack); // an error occurred
  } else {
    console.log(`Detected labels for: ${photo}`)

    response.Labels.forEach(label => {
      console.log(`Label:      ${label.Name}`)
      console.log(`Confidence: ${label.Confidence}`)
      console.log("Instances:")
      label.Instances.forEach(instance => {
        let box = instance.BoundingBox
        console.log("  Bounding box:")
        console.log(`    Top:        ${box.Top}`)
        console.log(`    Left:       ${box.Left}`)
        console.log(`    Width:      ${box.Width}`)
        console.log(`    Height:     ${box.Height}`)
        console.log(`  Confidence: ${instance.Confidence}`)
      })
      console.log("Parents:")
      label.Parents.forEach(parent => {
        console.log(`  ${parent.Name}`)
      })
      console.log("------------")
      console.log("")
    }) // for response.labels
  } // if
});

cannot start streamprocessor

Stream processor fails when trying to start with the AWS CLI. I believe it has something to do with the role-arn because here is the output of when I invoke the describe-stream-processor command:

aws rekognition describe-stream-processor --name facedetectstreamprocessor
1527352315.942 1527352346.269 mystreamprocessor arn:aws:iam::123456789012:role/kinesisstreamrole FAILED Access denied to Role arn:aws:rekognition:us-east-1:123456789012:streamprocessor/facedetectstreamprocessor
KINESISVIDEOSTREAM arn:aws:kinesisvideo:us-east-1:123456789012:stream/videostreamtest
KINESISDATASTREAM arn:aws:kinesis:us-east-1:123456789012:stream/facedetectstream
FACESEARCH facestodetect 80.0

Invoking start_stream_processor has no errors, but when I look up status it says FAILED:

aws rekognition start-stream-processor --name facedetectstreamprocessor

aws rekognition list-stream-processors
STREAMPROCESSORS facedetectstreamprocessor FAILED

I am invoking these commands as the root user of my account.

Any help on this is appreciated - thanks!

No mention of required headers for requests via REST

I tried to test the endpoints using Postman, just to ascertain that the keys I had generated had appropriate permissions for using rekognition services. Took me an incredibly long time to realize I had to pass a x-amz-target and a content-type header, because the documentation just does not mention them. At all.

Nowhere in your documentation can I find COMPREHENSIVE details on how to test rekognition (or any other amazon services) via REST, which is problematic for any frameworks or stacks that do not have active SDKs provided out of the box.

SearchFaces throws InvalidParameterException: faceId was not found in the collection

Using java library software.amazon.awssdk:rekognition:2.16.54 got strange behaviour during search face method.
Case:

  1. Got 2 image. First image is man with document. Second is scan of document
  2. Creating collection
  3. Indexing first image and got 2 faces.
  4. calling search face (of man) for finding face from document
  5. Indexing second image :
ixFacesResp = rkgClient.indexFaces(
                            IndexFacesRequest.builder()
                                .collectionId(tempCollectionId)
                                .image(docImage)
                                .qualityFilter(QualityFilter.NONE)
                                .detectionAttributes(Attribute.ALL)
                                .maxFaces(1)
                                .build()
  1. calling search face (of face from indexed doc) for finding matches in previous two:
 if (ixFacesResp.hasFaceRecords()) {
                            val searchFaces = rkgClient.searchFaces(
                                SearchFacesRequest.builder()
                                    .faceId(ixFacesResp.faceRecords()[0].face().faceId())
                                    .collectionId(tempCollectionId)
                                    .build()
                            )
}

Receive:

software.amazon.awssdk.services.rekognition.model.InvalidParameterException: faceId was not found in the collection. (Service: Rekognition, Status Code: 400, Request ID: 2954c06f-5b32-4ed3-ad21-ebe339e93dd4, Extended Request ID: null)
	at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleErrorResponse(CombinedResponseHandler.java:123)
	at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleResponse(CombinedResponseHandler.java:79)
	at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handle(CombinedResponseHandler.java:59)
	at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handle(CombinedResponseHandler.java:40)
	at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:40)
	at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:30)
	at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
	at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:73)
	at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:42)
	at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:78)
	at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:40)
	at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptMetricCollectionStage.execute(ApiCallAttemptMetricCollectionStage.java:50)
	at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptMetricCollectionStage.execute(ApiCallAttemptMetricCollectionStage.java:36)
........

How it possible if i successfully received ixFacesResp at previous step and got non empty collection of matches ?
And it never fails at step 4 in spite of same code calling. Is it possible of getting Face object but empty faceId field ?

Wanted to post it in aws forums but due to 'hell' of registration, temporary can't do it.

Help Wanted – Troubleshooting Tips, Tricks, and Strategies

As you know, troubleshooting Amazon Rekognition can be a challenge. What issues have you run into getting Amazon Rekognition to work? Can you share your solutions with your colleagues? Please share only problems for which you've found a solution. If you're still struggling with a problem please contact Customer Support or post your issue on the Forums.

Share the following information with me as a response to this issue, and I'll consider adding it as troubleshooting information to the Amazon Rekognition documentation.
1. What were the symptoms of the problem?
2. Were the exception/error messages helpful or less than helpful? Did they help lead you to the solution, confuse you, or were they just white noise that didn't help or hurt? What specific message(s) did you get and how did they help or not help?
3. What did you do to troubleshoot? What did you try that didn't help? What finally did lead you to the correct root cause?
4. What did you finally do to correct the problem?

I'll use this information to improve the documentation - specifically the troubleshooting sections and descriptions of the exception messages. I'll also pass it relevant details on to the engineering team to possibly improve the error messages or the product itself. The more detail you can add, the better I can use it to improve things! Thank you very much, especially on behalf of all of your colleagues who run into the same problems!

Chris Rees

Senior Technical Writer

Amazon Rekognition
https://docs.aws.amazon.com/rekognition/latest/dg/what-is.html

Load testing issue

While doing load testing, we are getting below error.

HTTP/1.0 500 Internal Server Error
Date: Mon, 12 Apr 2021 11:18:35 GMT
Server: Apache
X-XSS-Protection: 1; mode=block
X-FRAME-OPTIONS: SAMEORIGIN
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8

We did 50 users, passed 42 users. Please help us to resolve the same. Testing and web server loads are normal.

java.lang.NullPointerException

I've used the same code. But Unfortunately, It is not working. What might be the possible reason?
(I have successfully implemented Objects_Labelling, Face_Detection, and Celebrity_Recognition on stored videos using aws rekognition. )

Following is the output. Any suggestions would be appreciated.

The result is,
Waiting for job: 9bf0dfe0912f48eb6621118c63b708bd2941edc9d01d4017587be1389b63193a
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
Job found was "9bf0dfe0912f48eb6621118c63b708bd2941edc9d01d4017587be1389b63193a"
Job id: "9bf0dfe0912f48eb6621118c63b708bd2941edc9d01d4017587be1389b63193a"
Status : "SUCCEEDED"
9bf0dfe0912f48eb6621118c63b708bd2941edc9d01d4017587be1389b63193a
Format: QuickTime / MOV
Codec: h264
Exception in thread "main" Duration: 26673
FrameRate: 16.496

Sec: 0Person number: 0
Matches in collection...
java.lang.NullPointerException
at Facial_Rekognition.GetResultsFaceSearchCollection(Facial_Rekognition.java:267)
at Facial_Rekognition.main(Facial_Rekognition.java:156)

Ruby and NodeJs Examples for Comparing Faces

https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html

There are no ruby and nodejs examples:

Screen Shot 2019-07-26 at 4 52 01 PM

I have ruby ported:

Screen Shot 2019-07-26 at 4 51 12 PM

# Add to your Gemfile
# gem 'aws-sdk-rekognition'

require 'aws-sdk-rekognition'

credentials = Aws::Credentials.new(
   ENV['AWS_ACCESS_KEY_ID'],
   ENV['AWS_SECRET_ACCESS_KEY']
)

bucket        = 'mybucket' # the bucketname without s3://
photo_source  = 'photo_target.png'
photo_target  = 'photo_source.png'

client   = Aws::Rekognition::Client.new credentials: credentials

attrs = {
  source_image: {
    s3_object: {
      bucket: bucket,
      name: photo_source
    },
  },
  target_image: {
    s3_object: {
      bucket: bucket,
      name: photo_target
    },
  },
  similarity_threshold: 70
}
response = client.compare_faces attrs
response.face_matches.each do |face_match|
  position   = face_match.face.bounding_box
  similarity = face_match.similarity
  puts "The face at: #{position.left}, #{position.top} matches with #{similarity} % confidence"
end

working on NodeJs

Data Type of Timestamp

Could you please add the explanation of Timestamp attribute? Is there any relevance between Timestamp and "frames" of the analyized video? Since I want to mark up BoundingBox in the video but I cannot figure out which BoundingBox should draw in which "frame".

Rekognition Error Handling redirect to proper Service Limit page

On the amazon-rekognition-developer-guide error handling page:https://docs.aws.amazon.com/rekognition/latest/dg/error-handling.html,
the link under ProvisionedThroughputExceededException redirects to https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_rekognition which is just the generic AWS Service Quotas page. Should that direct to https://docs.aws.amazon.com/general/latest/gr/rekognition.html or https://docs.aws.amazon.com/rekognition/latest/dg/limits.html?

Golang example for comparing faces

There is no Golang sample code available for detecting labels in Images at AWS Rekognition Developer Guide :
https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html

My Golang snippet works fine and Produces the desired Result:

package main

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/rekognition"
)

var svc *rekognition.Rekognition

func init() {

	sess, err := session.NewSession(&aws.Config{
		Region: aws.String("us-east-1"),
	})

	if err != nil {
		fmt.Println("Error while creating session,", err)
		return
	}

	svc = rekognition.New(sess)
	_ = svc
}

func main() {

	input := &rekognition.CompareFacesInput{

		SimilarityThreshold: aws.Float64(80),
		SourceImage: &rekognition.Image{

			S3Object: &rekognition.S3Object{
				Bucket: aws.String(""),
				Name:   aws.String(""),
			},

		},
		TargetImage: &rekognition.Image{

			S3Object: &rekognition.S3Object{
				Bucket: aws.String(""),
				Name:   aws.String(""),
			},

		},
	}

	resp, err := svc.CompareFaces(input)

	if err != nil { //If there is an Error
		fmt.Println(err.Error())
		return
	}


	for _, faceMatch := range resp.FaceMatches {

		position := faceMatch.Face.BoundingBox
		similarity := faceMatch.Similarity

		fmt.Printf(" The face at %v %v matches with %f confidence\n", *position.Left, *position.Top, *similarity )

	}

	fmt.Printf("Face Matches : %v\n", len(resp.FaceMatches))

}

aws-golang

Submitting a Pull Request with the above changes.

Face comparasion result

when i am comparing two images (source image is person id and target image is person image) in amazon console it gives 85% similarity score while the same images gives 16 % similarity programatically why this is happening i cant figure out
please help me ............ its been 4 days i havnt found any solution

Golang example for detecting labels in Image

There is no Golang sample code available for detecting labels in Images at AWS Rekognition Developer Guide :
https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html

My Golang snippet works fine and Produces the desired Result:

package main

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/rekognition"
)

var svc *rekognition.Rekognition

func init() {

	sess, err := session.NewSession(&aws.Config{
		Region: aws.String("us-east-1"),
	})

	if err != nil {
		fmt.Println("Error while creating session,", err)
		return
	}

	svc = rekognition.New(sess)
	_ = svc
}

func main() {

	bucket := "" //Bucket name from S3
	photo := ""       //Image File

	params := &rekognition.DetectLabelsInput{
		Image: &rekognition.Image{ // Required

			S3Object: &rekognition.S3Object{
				Bucket: aws.String(bucket),
				Name:   aws.String(photo),
			},
		},

		MaxLabels:     aws.Int64(10),
		MinConfidence: aws.Float64(70.000000),
	}

	resp, err := svc.DetectLabels(params)

	if err != nil { //If there is an Error
		fmt.Println(err.Error())
		return
	}

	fmt.Printf("Detected Labels for %s\n", photo)

	for _, label := range resp.Labels {

		fmt.Printf("Label : %v\n", *label.Name)
		fmt.Printf("Confidence : %v\n", *label.Confidence)
		fmt.Print("Instances:\n")

		for _, instance := range label.Instances {

			fmt.Print(" Bounding Box\n")
			fmt.Printf("	Top: %v\n", *instance.BoundingBox.Top)
			fmt.Printf("	Left: %v\n", *instance.BoundingBox.Left)
			fmt.Printf("	Width: %v\n", *instance.BoundingBox.Width)
			fmt.Printf("	Height: %v\n", *instance.BoundingBox.Height)
			fmt.Printf("	Confidence: %v\n", *instance.Confidence)
		}

		fmt.Print("Parents:\n")
		for _, parent := range label.Parents {
			fmt.Printf("	%v\n", *parent.Name)
		}

		fmt.Print("----------\n")
		fmt.Print("\n")

	}

}

detect-label

Submitting a Pull Request with the above changes.

Aws Rekognition stop-stream-processor results in error AccessDeniedException

Hello all,

I have created a stream-processor using AWS-cli using command -
aws rekognition create-stream-processor my-stream-processor with params....

it returned response as below:
{ "SessionId": "session-id" }

Assuming the processor started well, now I tried stopping this processor using AWS-cli using following command-
aws rekognition stop-stream-processor --name my-stream-processor

but its failing with:

An error occurred (AccessDeniedException) when calling the StopStreamProcessor operation

Can anyone please help me out in understanding the cause of error and how to fix it?

--
Thanks,
Kanak

Ruby and NodeJs examples for Detecting Faces in an Image

https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html

No Ruby or NodeJs examples:
Screen Shot 2019-07-26 at 4 19 09 PM

I have ruby version ported

Screen Shot 2019-07-26 at 4 19 39 PM

# Add to your Gemfile
# gem 'aws-sdk-rekognition'

require 'aws-sdk-rekognition'

credentials = Aws::Credentials.new(
   ENV['AWS_ACCESS_KEY_ID'],
   ENV['AWS_SECRET_ACCESS_KEY']
)

bucket = 'mybucket' # the bucketname without s3://
photo  = 'photo.png'# the name of file

client   = Aws::Rekognition::Client.new credentials: credentials

attrs = {
  image: {
    s3_object: {
      bucket: bucket,
      name: photo
    },
  },
  attributes: ['ALL']
}
response = client.detect_faces attrs

puts "Detected faces for: #{photo}"
response.face_details.each do |face_detail|
  low  = face_detail.age_range.low
  high = face_detail.age_range.high
  puts "The detected face is between: #{low} and #{high} years old"
  puts "All other attributes:"
  puts "  bounding_box.width:     #{face_detail.bounding_box.width}"
  puts "  bounding_box.height:    #{face_detail.bounding_box.height}"
  puts "  bounding_box.left:      #{face_detail.bounding_box.left}"
  puts "  bounding_box.top:       #{face_detail.bounding_box.top}"
  puts "  age.range.low:          #{face_detail.age_range.low}"
  puts "  age.range.high:         #{face_detail.age_range.high}"
  puts "  smile.value:            #{face_detail.smile.value}"
  puts "  smile.confidence:       #{face_detail.smile.confidence}"
  puts "  eyeglasses.value:       #{face_detail.eyeglasses.value}"
  puts "  eyeglasses.confidence:  #{face_detail.eyeglasses.confidence}"
  puts "  sunglasses.value:       #{face_detail.sunglasses.value}"
  puts "  sunglasses.confidence:  #{face_detail.sunglasses.confidence}"
  puts "  gender.value:           #{face_detail.gender.value}"
  puts "  gender.confidence:      #{face_detail.gender.confidence}"
  puts "  beard.value:            #{face_detail.beard.value}"
  puts "  beard.confidence:       #{face_detail.beard.confidence}"
  puts "  mustache.value:         #{face_detail.mustache.value}"
  puts "  mustache.confidence:    #{face_detail.mustache.confidence}"
  puts "  eyes_open.value:        #{face_detail.eyes_open.value}"
  puts "  eyes_open.confidence:   #{face_detail.eyes_open.confidence}"
  puts "  mout_open.value:        #{face_detail.mouth_open.value}"
  puts "  mout_open.confidence:   #{face_detail.mouth_open.confidence}"
  puts "  emotions[0].type:       #{face_detail.emotions[0].type}"
  puts "  emotions[0].confidence: #{face_detail.emotions[0].confidence}"
  puts "  landmarks[0].type:      #{face_detail.landmarks[0].type}"
  puts "  landmarks[0].x:         #{face_detail.landmarks[0].x}"
  puts "  landmarks[0].y:         #{face_detail.landmarks[0].y}"
  puts "  pose.roll:              #{face_detail.pose.roll}"
  puts "  pose.yaw:               #{face_detail.pose.yaw}"
  puts "  pose.pitch:             #{face_detail.pose.pitch}"
  puts "  quality.brightness:     #{face_detail.quality.brightness}"
  puts "  quality.sharpness:      #{face_detail.quality.sharpness}"
  puts "  confidence:             #{face_detail.confidence}"
  puts "------------"
  puts ""
end

going to get NodeJS version and the commit them together

Incorrect behavior for DetectLabels method/docs in javascript SDK

Problem

When using the javascript SDK, the DetectLabels method returns a valid 200 response code, but no labels or confidence values when using the code snippet below from the documentation (live: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Rekognition.html#detectLabels-property)

Calling the detectLabels operation

var params = {
  Image: { /* required */
    Bytes: new Buffer('...') || 'STRING_VALUE' /* Strings will be Base-64 encoded on your behalf */,
    S3Object: {
      Bucket: 'STRING_VALUE',
      Name: 'STRING_VALUE',
      Version: 'STRING_VALUE'
    }
  },
  MaxLabels: 0,
  MinConfidence: 0.0
};
rekognition.detectLabels(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Resolution (Workaround)

While MaxLabels and MinConfidence being set to 0 should be as inclusive as possible (no limit to the number of response labels, with no minimum confidence required), a 200 response with no labels was returned until we removed them, at which point the same image would return valid labels and confidence values.

I'm not sure whether this is a mistake in the docs, the javascript SDK, or the backend service, just trying to pass along the bug and what made it occur. If there's somewhere else I should file a ticket for this, let me know.

AccessDeniedException when calling Create/List Stream Processor

Hi i'm trying to create stream processor from cli, but get stuck by creating new stream processor with the error message is:

An error occurred (AccessDeniedException) when calling the ListStreamProcessors operation:

My CLI command is:
aws rekognition create-stream-processor --input KinesisVideoStream={Arn="arn:aws:kinesisvideo:ap-southeast-2:1234567890:stream/redisys-stream/1552295399763"} --name "RdsStreamProcessor" --settings FaceSearch={"CollectionId=rds_customers,FaceMatchThreshold=90"} --role-arn "arn:aws:iam::1234567890:role/rds_recognition_role" --stream-processor-output KinesisDataStream={Arn="arn:aws:kinesis:ap-southeast-2:1234567890:stream/rds-face-recognition-stream"}

arn:aws:iam::1234567890:role/rds_recognition_role:
Pocilies:

  1. AmazonRekognitionServiceRole
  2. Policy with json:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
}

Trust relationships

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "rekognition.amazonaws.com"
      },
      "Action": "sts:AssumeRole",
      "Condition": {}
    }
  ]
}

I am invoking these commands as the root user of my account.

Any help on this is appreciated - thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.