

终止支持通知：2026 年 10 月 7 日， AWS 将停止对的支持。 AWS IoT Greengrass Version 1 2026 年 10 月 7 日之后，您将无法再访问这些 AWS IoT Greengrass V1 资源。如需了解更多信息，请访问[迁移自 AWS IoT Greengrass Version 1](https://docs.aws.amazon.com/greengrass/v2/developerguide/migrate-from-v1.html)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# ML 图像分类连接器
<a name="image-classification-connector"></a>

**警告**  <a name="connectors-extended-life-phase-warning"></a>
此连接器已进入*生命周期延长阶段*， AWS IoT Greengrass 不会发布更新来提供功能、现有功能增强、安全补丁或错误修复。有关更多信息，请参阅 [AWS IoT Greengrass Version 1 维护政策](maintenance-policy.md)。

ML 图像分类[连接器](connectors.md)提供在 AWS IoT Greengrass 核心上运行的机器学习 (ML) 推理服务。此局部推理服务使用由 SageMaker AI 图像分类算法训练的模型执行图像分类。

用户定义的 Lambda 函数使用 M AWS IoT Greengrass achine Learning SDK 向本地推理服务提交推理请求。该服务在本地运行推理，并返回输入映像属于特定类别的概率。

AWS IoT Greengrass 提供了此连接器的以下版本，可用于多个平台。

------
#### [ Version 2 ]


| Connector | 描述和 ARN | 
| --- | --- | 
| 机器学习图像分类 Aarch64 JTX2 |  适用于 NVIDIA Jet TX2 son 的图像分类推理服务。支持 GPU 加速。 **ARN**：`arn:aws:greengrass:region::/connectors/ImageClassificationAarch64JTX2/versions/2` | 
| ML 图像分类 x86\$164 |  适用于 x86\$164 平台的映像分类推理服务。 **ARN**：`arn:aws:greengrass:region::/connectors/ImageClassificationx86-64/versions/2` | 
| 机器学习图像分类 ARMv7 |   ARMv7 平台图像分类推理服务。 **ARN**：`arn:aws:greengrass:region::/connectors/ImageClassificationARMv7/versions/2` | 

------
#### [ Version 1 ]


| Connector | 描述和 ARN | 
| --- | --- | 
| 机器学习图像分类 Aarch64 JTX2 |  适用于 NVIDIA Jet TX2 son 的图像分类推理服务。支持 GPU 加速。 **ARN**：`arn:aws:greengrass:region::/connectors/ImageClassificationAarch64JTX2/versions/1` | 
| ML 图像分类 x86\$164 |  适用于 x86\$164 平台的映像分类推理服务。 **ARN**：`arn:aws:greengrass:region::/connectors/ImageClassificationx86-64/versions/1` | 
| ML 图像分类 Armv7 |  适用于 ARMv7 平台的映像分类推理服务。 **ARN**：`arn:aws:greengrass:region::/connectors/ImageClassificationARMv7/versions/1` | 

------

有关版本更改的信息，请参阅[更改日志](#image-classification-connector-changelog)。

## 要求
<a name="image-classification-connector-req"></a>

这些连接器具有以下要求：

------
#### [ Version 2 ]
+ AWS IoT Greengrass 核心软件 v1.9.3 或更高版本。
+ <a name="conn-req-py-3.7-and-3.8"></a>[Python](https://www.python.org/) 版本 3.7 或 3.8 已安装在核心设备上，并已添加到 PATH 环境变量中。
**注意**  <a name="use-runtime-py3.8"></a>
要使用 Python 3.8，请运行以下命令来创建从默认 Python 3.7 安装文件夹到已安装的 Python 3.8 二进制文件的符号链接。  

  ```
  sudo ln -s path-to-python-3.8/python3.8 /usr/bin/python3.7
  ```
这会将设备配置为满足 AWS IoT Greengrass的 Python 要求。
+ <a name="req-image-classification-framework"></a>安装在核心设备上的 Apache MXNet 框架的依赖关系。有关更多信息，请参阅 [在 AWS IoT Greengrass 核心上安装 MXNet 依赖关系](#image-classification-connector-config)。
+ <a name="req-image-classification-resource"></a>Greengrass 群组中的一种引用 AI 模型源的[机器学习资源](ml-inference.md#ml-resources)。 SageMaker 该模型必须通过 SageMaker AI 图像分类算法进行训练。有关更多信息，请参阅 *Amazon A SageMaker I 开发者指南*中的[图像分类算法](https://docs.aws.amazon.com/sagemaker/latest/dg/image-classification.html)。
+ <a name="req-image-classification-feedback"></a>添加到 Greengrass 组且已配置的 [ ML 反馈连接器](ml-feedback-connector.md)。仅当您要使用此连接器上传模型输入数据并将预测发布到 MQTT 主题时，这才是必需的。
+ <a name="req-image-classification-policy"></a>[Greengrass 组角色](group-role.md)，配置为允许对目标训练作业执行 `sagemaker:DescribeTrainingJob` 操作，如以下示例 IAM policy 中所示。

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "sagemaker:DescribeTrainingJob"
              ],
              "Resource": "arn:aws:sagemaker:us-east-1:123456789012:training-job/training-job-name"
          }
      ]
  }
  ```

------

  <a name="set-up-group-role"></a>对于组角色要求，您必须将角色配置为授予所需权限，并确保角色已添加到组中。有关更多信息，请参阅[管理 Greengrass 组角色（控制台）](group-role.md#manage-group-role-console)或[管理 Greengrass 组角色 (CLI)](group-role.md#manage-group-role-cli)。

  您可以授予对资源的具体或条件访问权限（例如，通过使用通配符\$1命名方案）。如果将来要更改目标训练任务，请务必更新组角色。
+ AWS IoT Greengrass 需要使用 M@@ [achine Learning SDK](lambda-functions.md#lambda-sdks-ml) v1.1.0 才能与此连接器进行交互。

------
#### [ Version 1 ]
+ AWS IoT Greengrass 核心软件 v1.7 或更高版本。
+ [Python](https://www.python.org/) 版本 2.7 已安装在核心设备上，并已添加到 PATH 环境变量中。
+ <a name="req-image-classification-framework"></a>安装在核心设备上的 Apache MXNet 框架的依赖关系。有关更多信息，请参阅 [在 AWS IoT Greengrass 核心上安装 MXNet 依赖关系](#image-classification-connector-config)。
+ <a name="req-image-classification-resource"></a>Greengrass 群组中的一种引用 AI 模型源的[机器学习资源](ml-inference.md#ml-resources)。 SageMaker 该模型必须通过 SageMaker AI 图像分类算法进行训练。有关更多信息，请参阅 *Amazon A SageMaker I 开发者指南*中的[图像分类算法](https://docs.aws.amazon.com/sagemaker/latest/dg/image-classification.html)。
+ <a name="req-image-classification-policy"></a>[Greengrass 组角色](group-role.md)，配置为允许对目标训练作业执行 `sagemaker:DescribeTrainingJob` 操作，如以下示例 IAM policy 中所示。

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "sagemaker:DescribeTrainingJob"
              ],
              "Resource": "arn:aws:sagemaker:us-east-1:123456789012:training-job/training-job-name"
          }
      ]
  }
  ```

------

  <a name="set-up-group-role"></a>对于组角色要求，您必须将角色配置为授予所需权限，并确保角色已添加到组中。有关更多信息，请参阅[管理 Greengrass 组角色（控制台）](group-role.md#manage-group-role-console)或[管理 Greengrass 组角色 (CLI)](group-role.md#manage-group-role-cli)。

  您可以授予对资源的具体或条件访问权限（例如，通过使用通配符\$1命名方案）。如果将来要更改目标训练任务，请务必更新组角色。
+ AWS IoT Greengrass 需要使用 M@@ [achine Learning SDK](lambda-functions.md#lambda-sdks-ml) v1.0.0 或更高版本才能与此连接器进行交互。

------

## 连接器参数
<a name="image-classification-connector-param"></a>

这些连接器提供以下参数。

------
#### [ Version 2 ]

`MLModelDestinationPath`  <a name="param-image-classification-mdlpath"></a>
Lambda 环境中 ML 资源的本地绝对路径。这是为 ML 资源指定的目标路径。  
如果您在控制台中创建了 ML 资源，这便是本地路径。
 AWS IoT 控制台中的显示名称：**模型目标路径**  
必需：`true`  
类型：`string`  
有效模式：`.+`

`MLModelResourceId`  <a name="param-image-classification-mdlresourceid"></a>
引用源模型的 ML 资源的 ID。  
 AWS IoT 控制台中的显示名称：**SageMaker 作业 ARN 资源**  
必需：`true`  
类型：`string`  
有效模式：`[a-zA-Z0-9:_-]+`

`MLModelSageMakerJobArn`  <a name="param-image-classification-mdljobarn"></a>
代表 AI 模型来源的 SageMaker AI 训练作业的 SageMaker ARN。模型必须通过 SageMaker AI 图像分类算法进行训练。  
 AWS IoT 控制台中的显示名称：**SageMaker 作业 ARN**  
必需：`true`  
类型：`string`  
有效模式：`^arn:aws:sagemaker:[a-zA-Z0-9-]+:[0-9]+:training-job/[a-zA-Z0-9][a-zA-Z0-9-]+$`

`LocalInferenceServiceName`  <a name="param-image-classification-svcname"></a>
本地推理服务的名称。用户定义的 Lambda 函数通过将名称传递给 Machine Learn AWS IoT Greengrass ing SD `invoke_inference_service` K 的函数来调用服务。有关示例，请参阅[用法示例](#image-classification-connector-usage)。  
 AWS IoT 控制台中的显示名称：**本地推理服务**名称  
必需：`true`  
类型：`string`  
有效模式：`[a-zA-Z0-9][a-zA-Z0-9-]{1,62}`

`LocalInferenceServiceTimeoutSeconds`  <a name="param-image-classification-svctimeout"></a>
在推理请求终止之前经过的时间（以秒为单位）。最小值为 1。  
 AWS IoT 控制台中的显示名称：**超时（秒）**  
必需：`true`  
类型：`string`  
有效模式：`[1-9][0-9]*`

`LocalInferenceServiceMemoryLimitKB`  <a name="param-image-classification-svcmemorylimit"></a>
该服务有权访问的内存量（以 KB 为单位）。最小值为 1。  
 AWS IoT 控制台中的显示名称：**内存限制 (KB)**  
必需：`true`  
类型：`string`  
有效模式：`[1-9][0-9]*`

`GPUAcceleration`  <a name="param-image-classification-gpuacceleration"></a>
CPU 或 GPU（加速）计算上下文。此属性仅适用于 ML 图像分类 Aarch64 JTX2 连接器。  
 AWS IoT 控制台中的显示名称：**GPU 加速**  
必需：`true`  
类型：`string`  
有效值：`CPU` 或 `GPU`

`MLFeedbackConnectorConfigId`  <a name="param-image-classification-feedbackconfigid"></a>
用于上传模型输入数据的反馈配置的 ID。这必须与为 [ML 反馈连接器](ml-feedback-connector.md)定义的反馈配置的 ID 匹配。  
仅当您要使用 ML 反馈连接器上传模型输入数据并将预测发布到 MQTT 主题时，才需要此参数。  
 AWS IoT 控制台中的显示名称：**ML 反馈连接器配置 ID**  
必需：`false`  
类型：`string`  
有效模式：`^$|^[a-zA-Z0-9][a-zA-Z0-9-]{1,62}$`

------
#### [ Version 1 ]

`MLModelDestinationPath`  <a name="param-image-classification-mdlpath"></a>
Lambda 环境中 ML 资源的本地绝对路径。这是为 ML 资源指定的目标路径。  
如果您在控制台中创建了 ML 资源，这便是本地路径。
 AWS IoT 控制台中的显示名称：**模型目标路径**  
必需：`true`  
类型：`string`  
有效模式：`.+`

`MLModelResourceId`  <a name="param-image-classification-mdlresourceid"></a>
引用源模型的 ML 资源的 ID。  
 AWS IoT 控制台中的显示名称：**SageMaker 作业 ARN 资源**  
必需：`true`  
类型：`string`  
有效模式：`[a-zA-Z0-9:_-]+`

`MLModelSageMakerJobArn`  <a name="param-image-classification-mdljobarn"></a>
代表 AI 模型来源的 SageMaker AI 训练作业的 SageMaker ARN。模型必须通过 SageMaker AI 图像分类算法进行训练。  
 AWS IoT 控制台中的显示名称：**SageMaker 作业 ARN**  
必需：`true`  
类型：`string`  
有效模式：`^arn:aws:sagemaker:[a-zA-Z0-9-]+:[0-9]+:training-job/[a-zA-Z0-9][a-zA-Z0-9-]+$`

`LocalInferenceServiceName`  <a name="param-image-classification-svcname"></a>
本地推理服务的名称。用户定义的 Lambda 函数通过将名称传递给 Machine Learn AWS IoT Greengrass ing SD `invoke_inference_service` K 的函数来调用服务。有关示例，请参阅[用法示例](#image-classification-connector-usage)。  
 AWS IoT 控制台中的显示名称：**本地推理服务**名称  
必需：`true`  
类型：`string`  
有效模式：`[a-zA-Z0-9][a-zA-Z0-9-]{1,62}`

`LocalInferenceServiceTimeoutSeconds`  <a name="param-image-classification-svctimeout"></a>
在推理请求终止之前经过的时间（以秒为单位）。最小值为 1。  
 AWS IoT 控制台中的显示名称：**超时（秒）**  
必需：`true`  
类型：`string`  
有效模式：`[1-9][0-9]*`

`LocalInferenceServiceMemoryLimitKB`  <a name="param-image-classification-svcmemorylimit"></a>
该服务有权访问的内存量（以 KB 为单位）。最小值为 1。  
 AWS IoT 控制台中的显示名称：**内存限制 (KB)**  
必需：`true`  
类型：`string`  
有效模式：`[1-9][0-9]*`

`GPUAcceleration`  <a name="param-image-classification-gpuacceleration"></a>
CPU 或 GPU（加速）计算上下文。此属性仅适用于 ML 图像分类 Aarch64 JTX2 连接器。  
 AWS IoT 控制台中的显示名称：**GPU 加速**  
必需：`true`  
类型：`string`  
有效值：`CPU` 或 `GPU`

------

### 创建连接器示例 (AWS CLI)
<a name="image-classification-connector-create"></a>

以下 CLI 命令创建一个 `ConnectorDefinition`，它具有包含 ML 图像分类连接器的初始版本。

**示例：CPU 实例**  
以下示例创建 ML 图像分类 ARMv7l 连接器的实例。  

```
aws greengrass create-connector-definition --name MyGreengrassConnectors --initial-version '{
    "Connectors": [
        {
            "Id": "MyImageClassificationConnector",
            "ConnectorArn": "arn:aws:greengrass:region::/connectors/ImageClassificationARMv7/versions/2",
            "Parameters": {
                "MLModelDestinationPath": "/path-to-model",
                "MLModelResourceId": "my-ml-resource",
                "MLModelSageMakerJobArn": "arn:aws:sagemaker:us-west-2:123456789012:training-job:MyImageClassifier",
                "LocalInferenceServiceName": "imageClassification",
                "LocalInferenceServiceTimeoutSeconds": "10",
                "LocalInferenceServiceMemoryLimitKB": "500000",
                "MLFeedbackConnectorConfigId": "MyConfig0"
            }
        }
    ]
}'
```

**示例：GPU 实例**  
此示例创建了 ML 图像分类 Aarch64 JTX2 连接器的实例，该连接器支持 NVIDIA Jet TX2 son 主板上的 GPU 加速。  

```
aws greengrass create-connector-definition --name MyGreengrassConnectors --initial-version '{
    "Connectors": [
        {
            "Id": "MyImageClassificationConnector",
            "ConnectorArn": "arn:aws:greengrass:region::/connectors/ImageClassificationAarch64JTX2/versions/2",
            "Parameters": {
                "MLModelDestinationPath": "/path-to-model",
                "MLModelResourceId": "my-ml-resource",
                "MLModelSageMakerJobArn": "arn:aws:sagemaker:us-west-2:123456789012:training-job:MyImageClassifier",
                "LocalInferenceServiceName": "imageClassification",
                "LocalInferenceServiceTimeoutSeconds": "10",
                "LocalInferenceServiceMemoryLimitKB": "500000",
                "GPUAcceleration": "GPU",
                "MLFeedbackConnectorConfigId": "MyConfig0"
            }
        }
    ]
}'
```

**注意**  
这些连接器中的 Lambda 函数的生命周期[很长](lambda-functions.md#lambda-lifecycle)。

在 AWS IoT Greengrass 控制台中，您可以从群组的 “连接器” 页面添加**连接器**。有关更多信息，请参阅 [Greengrass 连接器入门（控制台）](connectors-console.md)。

## 输入数据
<a name="image-classification-connector-data-input"></a>

 这些连接器接受一个图像文件作为输入。输入图像文件必须为 `jpeg` 或 `png` 格式。有关更多信息，请参阅 [用法示例](#image-classification-connector-usage)。

这些连接器不接受 MQTT 消息作为输入数据。

## 输出数据
<a name="image-classification-connector-data-output"></a>

这些连接器返回输入图像中识别的对象的格式化预测：

```
[0.3,0.1,0.04,...]
```

预测包含值列表，这些值与模型训练期间训练数据集中使用的类别相对应。每个值代表图像落入相应类别的概率。概率最高的类别是主导预测。

这些连接器不发布 MQTT 消息来作为输出数据。

## 用法示例
<a name="image-classification-connector-usage"></a>

以下示例 Lambda 函数使用 [AWS IoT Greengrass 机器学习软件开发工具包](lambda-functions.md#lambda-sdks-ml) 与 ML 图像分类连接器进行交互。

**注意**  
 您可以从 [AWS IoT Greengrass 机器学习开发工具包](what-is-gg.md#gg-ml-sdk-download)下载页面下载软件开发工具包。

该示例初始化一个开发工具包客户端，并同步调用该开发工具包的 `invoke_inference_service` 函数来调用本地推理服务。它会传入算法类型、服务名称、映像类型和映像内容。然后，该示例会解析服务响应以获取概率结果（预测）。

------
#### [ Python 3.7 ]

```
import logging
from threading import Timer

import numpy as np

import greengrass_machine_learning_sdk as ml

# We assume the inference input image is provided as a local file
# to this inference client Lambda function.
with open('/test_img/test.jpg', 'rb') as f:
    content = bytearray(f.read())

client = ml.client('inference')

def infer():
    logging.info('invoking Greengrass ML Inference service')

    try:
        resp = client.invoke_inference_service(
            AlgoType='image-classification',
            ServiceName='imageClassification',
            ContentType='image/jpeg',
            Body=content
        )
    except ml.GreengrassInferenceException as e:
        logging.info('inference exception {}("{}")'.format(e.__class__.__name__, e))
        return
    except ml.GreengrassDependencyException as e:
        logging.info('dependency exception {}("{}")'.format(e.__class__.__name__, e))
        return

    logging.info('resp: {}'.format(resp))
    predictions = resp['Body'].read().decode("utf-8")
    logging.info('predictions: {}'.format(predictions))
    
    # The connector output is in the format: [0.3,0.1,0.04,...]
    # Remove the '[' and ']' at the beginning and end.
    predictions = predictions[1:-1]
    count = len(predictions.split(','))
    predictions_arr = np.fromstring(predictions, count=count, sep=',')

    # Perform business logic that relies on the predictions_arr, which is an array
    # of probabilities.
    
    # Schedule the infer() function to run again in one second.
    Timer(1, infer).start()
    return

infer()

def function_handler(event, context):
    return
```

------
#### [ Python 2.7 ]

```
import logging
from threading import Timer

import numpy

import greengrass_machine_learning_sdk as gg_ml

# The inference input image.
with open("/test_img/test.jpg", "rb") as f:
    content = f.read()

client = gg_ml.client("inference")


def infer():
    logging.info("Invoking Greengrass ML Inference service")

    try:
        resp = client.invoke_inference_service(
            AlgoType="image-classification",
            ServiceName="imageClassification",
            ContentType="image/jpeg",
            Body=content,
        )
    except gg_ml.GreengrassInferenceException as e:
        logging.info('Inference exception %s("%s")', e.__class__.__name__, e)
        return
    except gg_ml.GreengrassDependencyException as e:
        logging.info('Dependency exception %s("%s")', e.__class__.__name__, e)
        return

    logging.info("Response: %s", resp)
    predictions = resp["Body"].read()
    logging.info("Predictions: %s", predictions)

    # The connector output is in the format: [0.3,0.1,0.04,...]
    # Remove the '[' and ']' at the beginning and end.
    predictions = predictions[1:-1]
    predictions_arr = numpy.fromstring(predictions, sep=",")
    logging.info("Split into %s predictions.", len(predictions_arr))

    # Perform business logic that relies on predictions_arr, which is an array
    # of probabilities.

    # Schedule the infer() function to run again in one second.
    Timer(1, infer).start()


infer()


# In this example, the required AWS Lambda handler is never called.
def function_handler(event, context):
    return
```

------

Machine Lear AWS IoT Greengrass ning SDK 中的`invoke_inference_service`函数接受以下参数。


| 参数 | 说明 | 
| --- | --- | 
| `AlgoType` | 要用于推理的算法类型的名称。目前仅支持 `image-classification`。 必需：`true` 类型：`string` 有效值：`image-classification` | 
| `ServiceName` | 本地推理服务的名称。在配置了连接器时，使用为 `LocalInferenceServiceName` 参数指定的名称。 必需：`true` 类型：`string` | 
| `ContentType` | 输入映像的 mime 类型。 必需：`true` 类型：`string` 有效值：`image/jpeg, image/png` | 
| `Body` | 输入映像文件的内容。 必需：`true` 类型：`binary` | 

## 在 AWS IoT Greengrass 核心上安装 MXNet 依赖关系
<a name="image-classification-connector-config"></a>

要使用 ML 图像分类连接器，必须在核心设备上安装 Apache MXNet 框架的依赖关系。连接器使用该框架来处理 ML 模型。

**注意**  
这些连接器与预编译的 MXNet 库捆绑在一起，因此您无需在核心设备上安装 MXNet 框架。

AWS IoT Greengrass 提供了用于安装以下常用平台和设备的依赖关系的脚本（或用作安装它们的参考）。如果您使用的是其他平台或设备，请参阅有关您的配置的[MXNet 文档](https://mxnet.apache.org/)。

在安装 MXNet 依赖关系之前，请确保设备上存在所需的[系统库](#image-classification-connector-logging)（具有指定的最低版本）。

------
#### [ NVIDIA Jetson TX2 ]

1. 安装 CUDA Toolkit 9.0 和 cuDNN 7.0。您可以按照入门教程中[设置其他设备](setup-filter.other.md)中的说明进行操作。

1. 启用通用存储库，以便连接器可以安装社区维护的开放软件。有关更多信息，请参阅 Ubuntu 文档中的 [Repositories/Ubuntu](https://help.ubuntu.com/community/Repositories/Ubuntu)。

   1. 打开 `/etc/apt/sources.list` 文件。

   1. 确保以下各行已取消注释。

      ```
      deb http://ports.ubuntu.com/ubuntu-ports/ xenial universe
      deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial universe
      deb http://ports.ubuntu.com/ubuntu-ports/ xenial-updates universe
      deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-updates universe
      ```

1. 将以下安装脚本的副本保存到核心设备上一个名为 `nvidiajtx2.sh` 的文件。

------
#### [ Python 3.7 ]

   ```
   #!/bin/bash
   set -e
   
   echo "Installing dependencies on the system..."
   echo 'Assuming that universe repos are enabled and checking dependencies...'
   apt-get -y update
   apt-get -y dist-upgrade
   apt-get install -y liblapack3 libopenblas-dev liblapack-dev libatlas-base-dev
   apt-get install -y python3.7 python3.7-dev
   
   python3.7 -m pip install --upgrade pip
   python3.7 -m pip install numpy==1.15.0
   python3.7 -m pip install opencv-python || echo 'Error: Unable to install OpenCV with pip on this platform. Try building the latest OpenCV from source (https://github.com/opencv/opencv).'
   
   echo 'Dependency installation/upgrade complete.'
   ```

**注意**  
<a name="opencv-build-from-source"></a>如果 [OpenCV](https://github.com/opencv/opencv) 使用此脚本无法成功安装，您可以尝试从源代码进行构建。有关更多信息，请参阅 OpenCV 文档中的[在 Linux 中安装](https://docs.opencv.org/4.1.0/d7/d9f/tutorial_linux_install.html)，或参考您平台的其他在线资源。

------
#### [ Python 2.7 ]

   ```
   #!/bin/bash
   set -e
   
   echo "Installing dependencies on the system..."
   echo 'Assuming that universe repos are enabled and checking dependencies...'
   apt-get -y update
   apt-get -y dist-upgrade
   apt-get install -y liblapack3 libopenblas-dev liblapack-dev libatlas-base-dev python-dev
   
   echo 'Install latest pip...'
   wget https://bootstrap.pypa.io/get-pip.py
   python get-pip.py
   rm get-pip.py
   
   pip install numpy==1.15.0 scipy
   
   echo 'Dependency installation/upgrade complete.'
   ```

------

1. 从保存文件的目录中，运行以下命令：

   ```
   sudo nvidiajtx2.sh
   ```

------
#### [ x86\$164 (Ubuntu or Amazon Linux)  ]

1. 将以下安装脚本的副本保存到核心设备上一个名为 `x86_64.sh` 的文件。

------
#### [ Python 3.7 ]

   ```
   #!/bin/bash
   set -e
   
   echo "Installing dependencies on the system..."
   
   release=$(awk -F= '/^NAME/{print $2}' /etc/os-release)
   
   if [ "$release" == '"Ubuntu"' ]; then
     # Ubuntu. Supports EC2 and DeepLens. DeepLens has all the dependencies installed, so
     # this is mostly to prepare dependencies on Ubuntu EC2 instance.
     apt-get -y update
     apt-get -y dist-upgrade
   
     apt-get install -y libgfortran3 libsm6 libxext6 libxrender1
     apt-get install -y python3.7 python3.7-dev
   elif [ "$release" == '"Amazon Linux"' ]; then
     # Amazon Linux. Expect python to be installed already
     yum -y update
     yum -y upgrade
   
     yum install -y compat-gcc-48-libgfortran libSM libXrender libXext
   else
     echo "OS Release not supported: $release"
     exit 1
   fi
   
   python3.7 -m pip install --upgrade pip
   python3.7 -m pip install numpy==1.15.0
   python3.7 -m pip install opencv-python || echo 'Error: Unable to install OpenCV with pip on this platform. Try building the latest OpenCV from source (https://github.com/opencv/opencv).'
   
   echo 'Dependency installation/upgrade complete.'
   ```

**注意**  
<a name="opencv-build-from-source"></a>如果 [OpenCV](https://github.com/opencv/opencv) 使用此脚本无法成功安装，您可以尝试从源代码进行构建。有关更多信息，请参阅 OpenCV 文档中的[在 Linux 中安装](https://docs.opencv.org/4.1.0/d7/d9f/tutorial_linux_install.html)，或参考您平台的其他在线资源。

------
#### [ Python 2.7 ]

   ```
   #!/bin/bash
   set -e
   
   echo "Installing dependencies on the system..."
   
   release=$(awk -F= '/^NAME/{print $2}' /etc/os-release)
   
   if [ "$release" == '"Ubuntu"' ]; then
     # Ubuntu. Supports EC2 and DeepLens. DeepLens has all the dependencies installed, so
     # this is mostly to prepare dependencies on Ubuntu EC2 instance.
     apt-get -y update
     apt-get -y dist-upgrade
   
     apt-get install -y libgfortran3 libsm6 libxext6 libxrender1 python-dev python-pip
   elif [ "$release" == '"Amazon Linux"' ]; then
     # Amazon Linux. Expect python to be installed already
     yum -y update
     yum -y upgrade
   
     yum install -y compat-gcc-48-libgfortran libSM libXrender libXext python-pip
   else
     echo "OS Release not supported: $release"
     exit 1
   fi
   
   pip install numpy==1.15.0 scipy opencv-python
   
   echo 'Dependency installation/upgrade complete.'
   ```

------

1. 从保存文件的目录中，运行以下命令：

   ```
   sudo x86_64.sh
   ```

------
#### [ Armv7 (Raspberry Pi) ]

1. 将以下安装脚本的副本保存到核心设备上一个名为 `armv7l.sh` 的文件。

------
#### [ Python 3.7 ]

   ```
   #!/bin/bash
   set -e
   
   echo "Installing dependencies on the system..."
   
   apt-get update
   apt-get -y upgrade
   
   apt-get install -y liblapack3 libopenblas-dev liblapack-dev
   apt-get install -y python3.7 python3.7-dev
   
   python3.7 -m pip install --upgrade pip
   python3.7 -m pip install numpy==1.15.0
   python3.7 -m pip install opencv-python || echo 'Error: Unable to install OpenCV with pip on this platform. Try building the latest OpenCV from source (https://github.com/opencv/opencv).'
   
   echo 'Dependency installation/upgrade complete.'
   ```

**注意**  
<a name="opencv-build-from-source"></a>如果 [OpenCV](https://github.com/opencv/opencv) 使用此脚本无法成功安装，您可以尝试从源代码进行构建。有关更多信息，请参阅 OpenCV 文档中的[在 Linux 中安装](https://docs.opencv.org/4.1.0/d7/d9f/tutorial_linux_install.html)，或参考您平台的其他在线资源。

------
#### [ Python 2.7 ]

   ```
   #!/bin/bash
   set -e
   
   echo "Installing dependencies on the system..."
   
   apt-get update
   apt-get -y upgrade
   
   apt-get install -y liblapack3 libopenblas-dev liblapack-dev python-dev
   
   # python-opencv depends on python-numpy. The latest version in the APT repository is python-numpy-1.8.2
   # This script installs python-numpy first so that python-opencv can be installed, and then install the latest
   # numpy-1.15.x with pip
   apt-get install -y python-numpy python-opencv
   dpkg --remove --force-depends python-numpy
   
   echo 'Install latest pip...'
   wget https://bootstrap.pypa.io/get-pip.py
   python get-pip.py
   rm get-pip.py
   
   pip install --upgrade numpy==1.15.0 picamera scipy
   
   echo 'Dependency installation/upgrade complete.'
   ```

------

1. 从保存文件的目录中，运行以下命令：

   ```
   sudo bash armv7l.sh
   ```
**注意**  
在 Raspberry Pi 上，使用 `pip` 安装机器学习依赖项是一项内存密集型操作，可能会导致设备用尽内存，变得无法响应。解决办法是临时增加交换空间大小：  
在 `/etc/dphys-swapfile` 中，增加 `CONF_SWAPSIZE` 变量的值，然后运行以下命令重启 `dphys-swapfile`。  

   ```
   /etc/init.d/dphys-swapfile restart
   ```

------

## 日志记录和故障排除
<a name="image-classification-connector-logging"></a>

根据您的群组设置，事件和错误日志会写入日 CloudWatch 志、本地文件系统或两者兼而有之。此连接器中的日志使用前缀 `LocalInferenceServiceName`。如果连接器出现异常行为，请检查连接器日志。其中经常包含有用的调试信息，例如缺失 ML 库依赖项或连接器启动故障的原因。

如果将 AWS IoT Greengrass 组配置为写入本地日志，则连接器会将日志文件写入到`greengrass-root/ggc/var/log/user/region/aws/`。有关 Greengrass 日志记录的更多信息，请参阅 [使用 AWS IoT Greengrass 日志进行监控](greengrass-logs-overview.md)。

可以使用以下信息帮助解决 ML 图像分类连接器问题。

**所需系统库**

以下选项卡列出了每个 ML 图像分类连接器所需的系统库。

------
#### [ ML Image Classification Aarch64 JTX2 ]


| 图书馆 | 最低版本 | 
| --- | --- | 
| ld-linux-aarch64.so.1 | GLIBC\$12.17 | 
| libc.so.6 | GLIBC\$12.17 | 
| libcublas.so.9.0 | 不适用 | 
| libcudart.so.9.0 | 不适用 | 
| libcudnn.so.7 | 不适用 | 
| libcufft.so.9.0 | 不适用 | 
| libcurand.so.9.0 | 不适用 | 
| libcusolver.so.9.0 | 不适用 | 
| libgcc\$1s.so.1 | GCC\$14.2.0 | 
| libgomp.so.1 | GOMP\$14.0，OMP\$11.0 | 
| libm.so.6 | GLIBC\$12.23 | 
| libpthread.so.0 | GLIBC\$12.17 | 
| librt.so.1 | GLIBC\$12.17 | 
| libstdc\$1\$1.so.6 | GLIBCXX\$13.4.21，CXXABI\$11.3.8 | 

------
#### [ ML Image Classification x86\$164 ]


| 图书馆 | 最低版本 | 
| --- | --- | 
| ld-linux-x86-64.so.2 | GCC\$14.0.0 | 
| libc.so.6 | GLIBC\$12.4 | 
| libgfortran.so.3 | GFORTRAN\$11.0 | 
| libm.so.6 | GLIBC\$12.23 | 
| libpthread.so.0 | GLIBC\$12.2.5 | 
| librt.so.1 | GLIBC\$12.2.5 | 
| libstdc\$1\$1.so.6 | CXXABI\$11.3.8，GLIBCXX\$13.4.21 | 

------
#### [ ML Image Classification Armv7 ]


| 图书馆 | 最低版本 | 
| --- | --- | 
| ld-linux-armhf.so.3 | GLIBC\$12.4 | 
| libc.so.6 | GLIBC\$12.7 | 
| libgcc\$1s.so.1 | GCC\$14.0.0 | 
| libgfortran.so.3 | GFORTRAN\$11.0 | 
| libm.so.6 | GLIBC\$12.4 | 
| libpthread.so.0 | GLIBC\$12.4 | 
| librt.so.1 | GLIBC\$12.4 | 
| libstdc\$1\$1.so.6 | CXXABI\$11.3.8，CXXABI\$1ARM\$11.3.3，GLIBCXX\$13.4.20 | 

------

**问题**


| 症状 | 解决方案 | 
| --- | --- | 
|  在 Raspberry Pi 上，记录了以下错误消息，并且您没有使用摄像机：`Failed to initialize libdc1394`  |  运行以下命令以显示驱动程序： <pre>sudo ln /dev/null /dev/raw1394</pre> 此操作是临时的，符号链接将在重启后消失。请参阅您的 OS 分发手册以了解如何在重启时自动创建链接。  | 

## 许可证
<a name="image-classification-connector-license"></a>

ML 图像分类连接器包含以下第三方软件/许可：<a name="boto-3-licenses"></a>
+ [适用于 Python (Boto3) 的 AWS SDK](https://pypi.org/project/boto3/)/Apache 许可证 2.0
+ [botocore](https://pypi.org/project/botocore/)/Apache 许可证 2.0
+ [dateutil](https://pypi.org/project/python-dateutil/1.4/)/PSF 许可证
+ [docutils](https://pypi.org/project/docutils/)/BSD 许可证，GNU 通用公共许可证 (GPL)，Python 软件基金会许可证，公共领域
+ [jmespath](https://pypi.org/project/jmespath/)/MIT 许可证
+ [s3transfer](https://pypi.org/project/s3transfer/)/Apache 许可证 2.0
+ [urllib3](https://pypi.org/project/urllib3/)/MIT 许可证
+ [Deep Neural Network Library (DNNL)](https://github.com/intel/mkl-dnn)/Apache 许可证 2.0
+ [OpenMP\$1 运行时库](https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/optimization-and-programming-guide/openmp-support/openmp-library-support/openmp-run-time-library-routines.html)/请参阅 [Intel OpenMP 运行时库许可](#openmp-license)。
+ [mxnet](https://pypi.org/project/mxnet/)/Apache 许可证 2.0
+ <a name="six-license"></a>[six](https://github.com/benjaminp/six)/MIT

**Intel OpenMP 运行时库许可**。Intel® OpenMP\$1 运行时经过双重许可，具有商业 (COM) 许可证（作为 Intel® Parallel Studio XE Suite 产品的一部分）和 BSD 开源 (OSS) 许可证。

该连接器在 [Greengrass Core 软件许可协议](https://greengrass-release-license.s3.us-west-2.amazonaws.com/greengrass-license-v1.pdf)下发布。

## 更改日志
<a name="image-classification-connector-changelog"></a>

下表介绍每个版本连接器的更改。


| 版本 | 更改 | 
| --- | --- | 
| 2 | 添加了`MLFeedbackConnectorConfigId`参数以支持使用[机器学习反馈连接器](ml-feedback-connector.md)上传模型输入数据、向 MQTT 主题发布预测以及向 Amazon CloudWatch 发布指标。  | 
| 1 | 初始版本。  | 

<a name="one-conn-version"></a>Greengrass 组在一个时间上只能包含一个版本的连接器。有关升级连接器版本的信息，请参阅[升级连接器版本](connectors.md#upgrade-connector-versions)。

## 另请参阅
<a name="image-classification-connector-see-also"></a>
+ [使用 Greengrass 连接器与服务和协议集成](connectors.md)
+ [Greengrass 连接器入门（控制台）](connectors-console.md)
+ [Greengrass 连接器入门 (CLI)](connectors-cli.md)
+ [执行机器学习推理](ml-inference.md)
+ *Amazon A SageMaker I 开发者指南*中的@@ [图像分类算法](https://docs.aws.amazon.com/sagemaker/latest/dg/image-classification.html)