本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
偵測影像中的異常
若要使用訓練有素的 Amazon 視覺瞭望模型偵測影像中的異常,請呼叫DetectAnomalies操作。結果來自DetectAnomalies
包含布林預測,將影像分類為包含一或多個異常,以及預測的置信度值。如果模型是圖像分割模型,則結果還包括顯示不同類型異常位置的彩色遮色片。
您提供的圖像DetectAnomalies
必須具有與用於訓練模型的影像相同的寬度和高度尺寸。
DetectAnomalies
接受圖像為 PNG 或 JPG 格式的圖像。我們建議影像的編碼和壓縮格式與用於訓練模型的格式相同。例如,如果您使用 PNG 格式影像訓練模型,請呼叫DetectAnomalies
與 PNG 格式的圖像。
打電話之前DetectAnomalies
,您必須先使用StartModel
操作。如需詳細資訊,請參閱開始您的亞馬遜 Lookout for Vision 模型。您需支付模型執行的時間量 (以分鐘為單位),以及模型使用的異常偵測單位數量收費。如果您不使用模型,請使用StopModel
操作以停止模型。如需詳細資訊,請參閱停止您的亞馬遜 Lookout for Vision 模型。
呼叫 DetectAnomalies
要打電話DetectAnomalies
」中,指定下列項目:
下面的例子演示了如何調用DetectAnomalies
。您可以使用 Python 和 Java 實例中的函數響應來調用函數判斷影像是否異常。
- AWS CLI
-
此 AWS CLI 命令顯示 DetectAnomalies
CLI 操作的 JSON 輸出。變更下列輸入參數的值:
-
project name
使用您要使用的項目的名稱。
-
model version
使用您要使用的模型版本。
-
content type
與您要使用的圖像的類型。有效值為image/png
(PNG 格式圖像)和image/jpeg
(JPG 格式的圖像)。
-
file name
使用您要使用的圖像的路徑和文件名。確定檔案類型符合的值content-type
。
aws lookoutvision detect-anomalies --project-name project name
\
--model-version model version
\
--content-type content type
\
--body file name
\
--profile lookoutvision-access
- Python
-
如需完整的程式碼範例,請參閱GitHub。
def detect_anomalies(lookoutvision_client, project_name, model_version, photo):
"""
Calls DetectAnomalies using the supplied project, model version, and image.
:param lookoutvision_client: A Lookout for Vision Boto3 client.
:param project: The project that contains the model that you want to use.
:param model_version: The version of the model that you want to use.
:param photo: The photo that you want to analyze.
:return: The DetectAnomalyResult object that contains the analysis results.
"""
image_type = imghdr.what(photo)
if image_type == "jpeg":
content_type = "image/jpeg"
elif image_type == "png":
content_type = "image/png"
else:
logger.info("Invalid image type for %s", photo)
raise ValueError(
f"Invalid file format. Supply a jpeg or png format file: {photo}")
# Get images bytes for call to detect_anomalies
with open(photo, "rb") as image:
response = lookoutvision_client.detect_anomalies(
ProjectName=project_name,
ContentType=content_type,
Body=image.read(),
ModelVersion=model_version)
return response['DetectAnomalyResult']
- Java V2
-
public static DetectAnomalyResult detectAnomalies(LookoutVisionClient lfvClient, String projectName,
String modelVersion,
String photo) throws IOException, LookoutVisionException {
/**
* Creates an Amazon Lookout for Vision dataset from a manifest file.
* Returns after Lookout for Vision creates the dataset.
*
* @param lfvClient An Amazon Lookout for Vision client.
* @param projectName The name of the project in which you want to create a
* dataset.
* @param modelVersion The version of the model that you want to use.
*
* @param photo The photo that you want to analyze.
*
* @return DetectAnomalyResult The analysis result from DetectAnomalies.
*/
logger.log(Level.INFO, "Processing local file: {0}", photo);
// Get image bytes.
InputStream sourceStream = new FileInputStream(new File(photo));
SdkBytes imageSDKBytes = SdkBytes.fromInputStream(sourceStream);
byte[] imageBytes = imageSDKBytes.asByteArray();
// Get the image type. Can be image/jpeg or image/png.
String contentType = getImageType(imageBytes);
// Detect anomalies in the supplied image.
DetectAnomaliesRequest request = DetectAnomaliesRequest.builder().projectName(projectName)
.modelVersion(modelVersion).contentType(contentType).build();
DetectAnomaliesResponse response = lfvClient.detectAnomalies(request,
RequestBody.fromBytes(imageBytes));
/*
* Tip: You can also use the following to analyze a local file.
* Path path = Paths.get(photo);
* DetectAnomaliesResponse response = lfvClient.detectAnomalies(request, path);
*/
DetectAnomalyResult result = response.detectAnomalyResult();
String prediction = "Prediction: Normal";
if (Boolean.TRUE.equals(result.isAnomalous())) {
prediction = "Prediction: Anomalous";
}
// Convert confidence to percentage.
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(1);
String confidence = String.format("Confidence: %s", defaultFormat.format(result.confidence()));
// Log classification result.
String photoPath = "File: " + photo;
String[] imageLines = { photoPath, prediction, confidence };
logger.log(Level.INFO, "Image: {0}\nAnomalous: {1}\nConfidence {2}", imageLines);
return result;
}
// Gets the image mime type. Supported formats are image/jpeg and image/png.
private static String getImageType(byte[] image) throws IOException {
InputStream is = new BufferedInputStream(new ByteArrayInputStream(image));
String mimeType = URLConnection.guessContentTypeFromStream(is);
logger.log(Level.INFO, "Image type: {0}", mimeType);
if (mimeType.equals("image/jpeg") || mimeType.equals("image/png")) {
return mimeType;
}
// Not a supported file type.
logger.log(Level.SEVERE, "Unsupported image type: {0}", mimeType);
throw new IOException(String.format("Wrong image type. %s format isn't supported.", mimeType));
}
了解來自的回應DetectAnomalies
來自的回應DetectAnomalies
根據您訓練的模型類型 (分類模型或分段模型) 而有所不同。在這兩種情況下,響應都是DetectAnomalyResult物件。
分類模型
如果您的模型是圖像分類模型,來自的回應DetectAnomalies
包含以下內容:
-
IsAnomalous— 圖像包含一個或多個異常的布爾指示器。
-
信心— 亞馬遜的視覺瞭望在異常預測的準確性的信心 (IsAnomalous
).Confidence
是介於 0 和 1 之間的浮點值。較高的值表示信賴度越高。
-
來源— 有關傳遞給圖像的信息DetectAnomalies
。
{
"DetectAnomalyResult": {
"Source": {
"Type": "direct"
},
"IsAnomalous": true,
"Confidence": 0.9996867775917053
}
}
您可以通過檢查來確定圖像中是否異常IsAnomalous
欄位並確認Confidence
價值足以滿足您的需求。
如果您找到傳回的置信度值DetectAnomalies
太低,請考慮重新訓練模型。如需範例程式碼,請參閱分類。
分割模型
如果您的模型是圖像分割模型,回應包括分類資訊和區段資訊,例如影像遮罩和異常類型。分類資訊是與區段資訊分開計算的,您不應該假設它們之間的關係。如果您在回應中未取得區段資訊,請檢查您是否擁有最新版本的AWS已安裝的 SDK (AWS Command Line Interface,如果您正在使用AWS CLI). 如需範例程式碼,請參閱分段和顯示分類和區段資訊。
IsAnomalous(分類) — 將影像分類為正常或異常的布林指示器。
信心(分類) — 亞馬遜的信心瞭望視覺在圖像的分類的準確性 (IsAnomalous
).Confidence
是介於 0 和 1 之間的浮點值。較高的值表示信賴度越高。
-
來源— 有關傳遞給圖像的信息DetectAnomalies
。
-
AnomalyMask(分割) — 涵蓋分析影像中發現異常的像素遮色片。影像上可能有多個異常。遮色片貼圖的顏色表示異常的類型。遮色片顏色會對應至指派給訓練資料集中異常類型的顏色。若要從遮色片顏色尋找異常類型,請核取Color
在PixelAnomaly
中傳回的每個異常的欄位Anomalies
列表。如需範例程式碼,請參閱顯示分類和區段資訊。
-
異常(分割) — 在影像中找到的異常清單。每個異常包括異常類型 (Name
) 和像素資訊 (PixelAnomaly
).TotalPercentageArea
是異常覆蓋的影像百分比區域。Color
是異常的遮色片顏色。
清單中的第一個元素永遠是代表影像背景的異常類型 (BACKGROUND
),並且不應該被視為異常。亞馬遜視覺觀察會自動將背景異常類型添加到響應中。您不需要在資料集中宣告背景異常類型。
{
"DetectAnomalyResult": {
"Source": {
"Type": "direct"
},
"IsAnomalous": true,
"Confidence": 0.9996814727783203,
"Anomalies": [
{
"Name": "background",
"PixelAnomaly": {
"TotalPercentageArea": 0.998999834060669,
"Color": "#FFFFFF"
}
},
{
"Name": "scratch",
"PixelAnomaly": {
"TotalPercentageArea": 0.0004034999874420464,
"Color": "#7ED321"
}
},
{
"Name": "dent",
"PixelAnomaly": {
"TotalPercentageArea": 0.0005966666503809392,
"Color": "#4DD8FF"
}
}
],
"AnomalyMask": "iVBORw0....."
}
}