ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

AWS SDK for Python(Boto3)调用 Amazon Rekognition 完整实战指南

AWS SDK for Python(Boto3)调用 Amazon Rekognition 完整实战指南 示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载导读本文基于 aws-doc-sdk-examples 仓库中 python/example_code/rekognition/README.md 及其配套源码系统讲解如何使用 AWS SDK for PythonBoto3操作 Amazon Rekognition完成人脸检测与比对、标签识别、名人识别、不当内容审核、图片文字识别、人脸集合Collection检索以及视频级的人脸/人物/名人/内容审核检测。读完本文你将掌握每个 Rekognition 服务 API 的 Boto3 调用方式、核心参数含义、运行与测试方法并能基于仓库源码快速搭建自己的图像与视频分析应用。概览示例代码在仓库中的组织方式本示例位于仓库的python/example_code/rekognition目录包含以下核心文件文件作用rekognition_image_detection.py图像检测场景人脸、标签、名人、审核标签、文字识别与比对rekognition_collections.py人脸集合场景创建集合、索引人脸、搜索匹配人脸、删除集合rekognition_video_detection.py视频检测场景标签、人脸、人物跟踪、名人、内容审核的异步任务rekognition_objects.py将服务返回结果封装为 Python 对象的辅助模块并提供绘制边界框/多边形的工具函数custom_labels_csv_to_manifest.py工具脚本将 CSV 标注文件转换为 Custom Labels 图像分类 manifest 文件requirements.txt运行示例所需依赖test/对应的单元测试其中图像与视频检测能力由RekognitionImage、RekognitionVideo两个薄封装类对外提供人脸集合能力由RekognitionCollection、RekognitionCollectionManager提供结果对象封装在rekognition_objects.py中。这些类都是对 Boto3 Rekognition API 的“薄封装”源码注释中明确写明了这一点因此阅读源码即可对照出每个 API 调用的真实参数。环境准备与依赖安装运行这些示例前需要先完成两件事一是满足 AWS 账号与 SDK 配置等前置条件详见 python/README.md 中的 Prerequisites 一节二是在虚拟环境中安装依赖。本目录的 requirements.txt 内容如下boto31.26.79 pillow9.4.0 pytest7.2.1 requests2.28.2安装命令README 原文python -m pip install -r requirements.txt各依赖的用途从源码中可以确认boto3Rekognition 服务客户端与 S3、IAM、SNS、SQS 等资源客户端的基础pillowPIL在 rekognition_objects.py 中被用于打开图片、绘制边界框和多边形并调用默认查看器展示结果requests演示脚本通过它从公开 URL 下载测试图片如dhei5unw3vrsx.cloudfront.net和测试视频pytest运行 test/ 目录下的单元测试。提示演示脚本默认从当前目录的.media文件夹读取本地图片如rekognition_image_detection.py的 usage demo 引用.media/pexels-kaique-rocha-109919.jpg。源码 docstring 说明若未克隆完整仓库需要先自行下载这些图片文件到对应位置。单操作Single ActionsAPI 示例README 按“单操作”列出 15 个服务 API 调用示例全部位于两个主文件中。下表给出完整清单及源码位置API 操作封装方法源码位置DetectFacesRekognitionImage.detect_faces()rekognition_image_detection.py#L96CompareFacesRekognitionImage.compare_faces()rekognition_image_detection.py#L117DetectLabelsRekognitionImage.detect_labels()rekognition_image_detection.py#L156DetectModerationLabelsRekognitionImage.detect_moderation_labels()rekognition_image_detection.py#L178DetectTextRekognitionImage.detect_text()rekognition_image_detection.py#L207RecognizeCelebritiesRekognitionImage.recognize_celebrities()rekognition_image_detection.py#L226CreateCollectionRekognitionCollectionManager.create_collection()rekognition_collections.py#L323DescribeCollectionRekognitionCollection.describe_collection()rekognition_collections.py#L84DeleteCollectionRekognitionCollection.delete_collection()rekognition_collections.py#L111IndexFacesRekognitionCollection.index_faces()rekognition_collections.py#L126ListFacesRekognitionCollection.list_faces()rekognition_collections.py#L167SearchFacesByImageRekognitionCollection.search_faces_by_image()rekognition_collections.py#L193SearchFacesRekognitionCollection.search_faces()rekognition_collections.py#L241DeleteFacesRekognitionCollection.delete_faces()rekognition_collections.py#L280ListCollectionsRekognitionCollectionManager.list_collections()rekognition_collections.py#L346图像输入Bytes 与 S3Object 两种方式所有图像检测方法都接收一个Image参数其格式由RekognitionImage的两个工厂方法确定rekognition_image_detection.py#L59-L94RekognitionImage.from_file()读取本地文件字节构造{Bytes: img_file.read()}适合本地小图若调用方未指定image_name默认以文件名为图片名。RekognitionImage.from_bucket()仅记录 S3 桶名与对象键构造{S3Object: {Bucket: ..., Name: ...}}图片在后续 API 调用时才真正被获取适合存放在 S3 中的图片。人脸检测与比对detect_faces()调用rekognition_client.detect_faces(Image..., Attributes[ALL])rekognition_image_detection.py#L104-L105Attributes[ALL]表示返回全部人脸属性年龄区间、性别、情绪、配饰等结果中的FaceDetails被逐个封装为RekognitionFace对象。compare_faces()调用compare_faces(SourceImage..., TargetImage..., SimilarityThresholdsimilarity)rekognition_image_detection.py#L130-L134将本图人脸与目标图中最大的人脸比对返回匹配人脸与未匹配人脸两个列表SimilarityThreshold为相似度阈值低于该值的人脸会被归入未匹配列表。标签、审核标签与文字识别detect_labels(max_labels)调用detect_labels(Image..., MaxLabelsmax_labels)rekognition_image_detection.py#L165-L166MaxLabels限制返回标签的最大数量标签既可能是物体类别也可能是人物。detect_moderation_labels()调用detect_moderation_labels(Image...)用于识别可能对部分受众不适的内容返回的ModerationLabels封装为RekognitionModerationLabel。detect_text()调用detect_text(Image...)从图像中识别文字如招牌、书本返回结果封装为RekognitionText每个文字元素包含DetectedText、TypeWORD/LINE、Id、ParentId、Confidence与Geometry含BoundingBox和Polygon。名人识别recognize_celebrities()调用recognize_celebrities(Image...)返回CelebrityFaces与UnrecognizedFaces两个列表分别封装为RekognitionCelebrity与RekognitionFace。RekognitionCelebrity对象包含名人Name、Id、信息Urls、MatchConfidence以及其Face对象rekognition_objects.py#L156-L174。人脸集合操作集合相关操作由两个类提供rekognition_collections.pyRekognitionCollectionManager负责create_collection(collection_id)调用create_collection(CollectionId...)与list_collections(max_results)调用list_collections(MaxResults...)。RekognitionCollection封装单个集合构造时从create_collection/describe_collection返回数据中解包CollectionArn、FaceCount、CreationTimestamp通过_unpack_collection并使用collection.get(...)兼容可选字段。其describe_collection()中有一处值得注意的兼容处理源码用response[CollectionArn] response.get(CollectionARN)来规避服务返回字段Arn与ARN大小写不一致的问题rekognition_collections.py#L95-L96。index_faces(image, max_faces)调用index_faces(CollectionId..., Image..., ExternalImageIdimage.image_name, MaxFaces..., DetectionAttributes[ALL])将图片中的人脸索引进集合返回FaceRecords中成功索引的人脸与UnindexedFaces中失败的人脸。索引成功的对象同时合并了Face集合索引信息与FaceDetail检测属性两部分数据。list_faces(max_results)调用list_faces(CollectionId..., MaxResults...)。search_faces_by_image(image, threshold, max_faces)调用search_faces_by_image(CollectionId..., Image..., FaceMatchThresholdthreshold, MaxFacesmax_faces)用参考图片中最大的脸去检索集合返回SearchedFaceBoundingBox、SearchedFaceConfidence组成的参考脸对象以及FaceMatches匹配列表。search_faces(face_id, threshold, max_faces)调用search_faces(CollectionId..., FaceId..., FaceMatchThreshold..., MaxFaces...)用集合内已有的一张脸按 FaceId去检索其他匹配人脸。delete_faces(face_ids)与delete_collection()分别调用delete_faces(CollectionId..., FaceIds...)与delete_collection(CollectionId...)返回被删除的人脸 ID 列表。场景一检测并展示图片中的元素README 中的场景“Detect and display elements in images”展示了用 Rekognition 检测图片元素并绘制边界框展示的过程对应脚本python rekognition_image_detection.py执行后usage_demo()rekognition_image_detection.py#L260会依次演示人脸检测读取街景图片detect_faces()找出人脸用show_bounding_boxes()绘制边界框展示标签检测detect_labels(100)找出图片标签对带Instances的标签绘制各自实例的边界框标签名与颜色一一对应最多 6 种颜色名人识别recognize_celebrities()识别名人并绘制边界框人脸比对通过requests.get下载两张网络图片用compare_faces(girl_image, group_image, 80)以 80% 相似度阈值比对参考脸与目标人脸组并高亮匹配人脸内容审核从 S3 桶console-sample-images-pdx的yoga_swimwear.jpg对象构造图片调用detect_moderation_labels()检测不当内容文字识别读取书本照片detect_text()识别文字用show_polygons()围绕每个文字元素的多边形轮廓绘制展示。边界框与多边形的绘制逻辑在 rekognition_objects.py#L22-L65 中实现Rekognition 返回的BoundingBoxLeft、Top、Width、Height与多边形顶点坐标都是相对图片尺寸的比例值01绘制时需乘上实际像素宽高例如left image.width * box[Left]。此外RekognitionFace的to_dict()rekognition_objects.py#L111-L149展示了如何从原始响应中提炼结构化摘要包括边界框、年龄区间age、性别、情绪仅保留置信度大于 50 的情绪类型、人脸/图片 ID以及微笑、眼镜、胡子、睁眼等布尔属性列表。场景二创建人脸集合并查找人脸README 中的场景“Build a collection and find faces in it”完整走通“创建集合 → 索引人脸 → 搜索匹配 → 删除集合”的闭环对应脚本python rekognition_collections.pyusage_demo()rekognition_collections.py#L370的步骤与源码实现如下构造图片列表从.media读取三张人物照片分别命名sitting、hopping、biking每个RekognitionImage都带自定义image_name该名称将作为IndexFaces的ExternalImageId写入集合创建集合collection_mgr.create_collection(doc-example-collection-demo)创建集合随后describe_collection()打印集合 ARN、人脸数、创建时间索引人脸对每张图片调用collection.index_faces(image, 10)MaxFaces10限制单张图片最多索引 10 张脸列出人脸collection.list_faces(10)列出集合中的人脸及其 FaceId按 FaceId 搜索collection.search_faces(faces[0].face_id, 80, 10)以 80% 为匹配阈值找出集合中与该 FaceId 相似的其他脸按图片搜索collection.search_faces_by_image(images[0], 80, 10)直接用第一张参考图片检索返回图中最大的人脸信息与集合中匹配的人脸列表清理最后调用collection.delete_collection()删除集合避免遗留资源。场景三检测视频中的人物与物体README 中的“Detect people and objects in a video”对应 rekognition_video_detection.py。与图片检测不同视频分析采用异步任务 通知机制视频必须先上传到 S3RekognitionVideo.from_bucket(s3_object, client)只记录桶与键rekognition_video_detection.py#L51-L62调用start_label_detection、start_face_detection、start_person_tracking、start_celebrity_recognition、start_content_moderation等启动任务得到JobId任务完成后通过get_label_detection等接口分页获取结果。通知通道SNS SQS IAM 角色create_notification_channel()rekognition_video_detection.py#L64-L148一次性创建整套通知设施SNS Topicsns_resource.create_topic(Nameresource_name)SQS 队列sqs_resource.create_queue(QueueName..., Attributes{ReceiveMessageWaitTimeSeconds: 5})启用长轮询等待 5 秒队列策略set_attributes写入一条允许 SNS Topic 向该队列SQS:SendMessage的策略并用Condition限定aws:SourceArn等于本 Topic ARN订阅self.topic.subscribe(Protocolsqs, Endpointqueue_arn)IAM 角色创建信任策略为rekognition.amazonaws.com的sts:AssumeRole角色并附加一条允许SNS:Publish到该 Topic 的内联策略iam_resource.create_policyrole.attach_policy。每次启动任务时get_notification_channel()返回{RoleArn: ..., SNSTopicArn: ...}作为NotificationChannel参数。poll_notification(job_id)rekognition_video_detection.py#L175-L198轮询队列读取消息 → 解析双层 JSON消息体与 Message 字段→ 校验JobId匹配 → 获取Status并删除消息。演示结束会调用delete_notification_channel()清理角色、策略、队列与 Topic。任务编排模板五个检测任务的“启动 → 轮询 → 取结果”流程复用同一模板_do_rekognition_job(job_description, start_job_func, get_results_func, result_extractor)rekognition_video_detection.py#L248-L268内部先_start_rekognition_job启动并返回 JobId再poll_notification等待完成若状态为SUCCEEDED则调用_get_rekognition_job_results提取结果否则返回空列表。各任务仅需传入对应的 Boto3 函数与结果提取 lambda例如标签检测提取response[Labels]中的Label与Timestamp人物跟踪提取response[Persons]中的Person与Timestamp并封装为RekognitionPerson每个被跟踪人物通过Index区分。工具脚本CSV 转 Custom Labels ManifestREADME 特别提到一个配套工具 custom_labels_csv_to_manifest.py用于将 CSV 标注文件转换为 Amazon Rekognition Custom Labels 的图像级分类manifest 文件支持一张图片对应多个图像级标签。CSV 的格式约定为image,label,label,...即第一列为图片引用后续列是标签名。若图片位于 S3可用--s3_path参数指定桶与文件夹前缀未指定时默认第一列已包含完整 S3 路径。用法示例python custom_labels_csv_to_manifest.py images.csv --s3_path s3://my-bucket/images/脚本执行流程源码可完整验证去重检查check_duplicates()custom_labels_csv_to_manifest.py#L26-L72以第一列为 key 检测重复图片若有重复生成name-duplicates.csv重复项与name-deduplicated.csv仅保留首次出现并提示用户修正后重跑若无重复则删除两个临时文件。生成 manifestcreate_manifest_file()custom_labels_csv_to_manifest.py#L75-L137对 CSV 每行生成一行 JSONJSON Lines 格式source-ref指向图片s3_path 第一列每个标签生成形如{标签名}: 1的字段并附带{标签名}-metadata元数据其中confidence1、job-namelabeling-job/标签名、class-name标签名、human-annotatedyes、UTC 格式的creation-date、typegroundtruth/image-classification空标签列会被跳过。输出得到csv文件名.manifest文件并打印处理的图片数与标签数。运行测试本目录测试位于 test/包含四个测试文件test_rekognition_image_detection.py覆盖图像检测各方法test_rekognition_collections.py覆盖集合创建、描述、删除、索引、列出、搜索、删脸test_rekognition_video_detection.py覆盖通知通道创建对 create_topic、create_queue、set_queue_attributes、subscribe、create_role、create_policy、attach_role_policy 的调用链均做了 stub及各检测任务test_custom_labels_csv_to_manifest.py覆盖 CSV 转 manifest 工具。测试通过 conftest.py 引入仓库test_tools中的通用 fixtures并使用make_faces、make_labels、make_persons、make_moderation_labels、make_texts等 fixture 构造与服务返回结构一致的测试数据。测试用例普遍采用pytest.mark.parametrize(error_code, [None, TestException])双路径验证正常路径断言返回值异常路径断言抛出ClientError且错误码匹配。运行测试的方式请参考 python/README.md 中的 Tests 一节。注意README 明确提示运行这些测试同样可能产生 AWS 费用。费用与安全注意事项费用运行示例代码可能产生 AWS 账户费用AWS Pricing 与 Free Tier运行测试同样可能产生费用最小权限原则建议按最小权限授予代码所需的 IAM 权限只授予完成任务所需的最少权限Grant least privilege区域可用性示例代码并非在每个 AWS 区域都经过测试请参考 AWS Regional Services 确认所用区域的可用性资源清理视频演示脚本在结束时会删除通知通道相关资源与 S3 桶rekognition_video_detection.py#L428-L432集合演示会删除集合避免产生持续费用。相关场景扩展README 还引用了两个跨服务场景Detect objects in images基于 Rekognition 按类别检测图片物体的应用位于 python/cross_service/photo_analyzerDetect people and objects in a video即上文讲解的 rekognition_video_detection.py 视频检测实现。参考资源更多官方资料可进一步查阅Amazon Rekognition Developer Guide、Amazon Rekognition API Reference以及 Boto3 文档中 Amazon Rekognition 服务的客户端参考。本仓库中对应的 SDK 源码实现与测试用例python/example_code/rekognition是理解每个 API 调用参数与响应结构的首选资料。赞分享示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载相关推荐使用 AWS SDK for PythonBoto3操作 Amazon SQS 的完整实战指南使用 AWS SDK for PythonBoto3操作 Amazon SQS 的完整实战指南 导读 本文以 python/example_code/sqs示例工程教程后端基于 Amazon Rekognition 的照片分析 Web 应用AWS SDK for PythonBoto3跨服务实战指南基于 Amazon Rekognition 的照片分析 Web 应用AWS SDK for PythonBoto3跨服务实战指南 导读 本文围绕 phot示例工程教程后端使用 AWS SDK for PythonBoto3操作 Amazon Aurora完整示例与实战指南使用 AWS SDK for PythonBoto3操作 Amazon Aurora完整示例与实战指南 本指南以 python/example_code/示例工程教程后端创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表