---
comments: true
---
# Image Anomaly Detection Pipeline Tutorial
## 1. Introduction to Image Anomaly Detection Pipeline
Image anomaly detection is an image processing technique that identifies unusual or non-conforming patterns within images through analysis. It is widely applied in industrial quality inspection, medical image analysis, and security monitoring. By leveraging machine learning and deep learning algorithms, image anomaly detection can automatically recognize potential defects, anomalies, or abnormal behaviors in images, enabling us to promptly identify issues and take corresponding actions. The image anomaly detection system is designed to automatically detect and mark anomalies in images, enhancing work efficiency and accuracy.
The image anomaly detection pipeline includes an unsupervised anomaly detection module, with the following model benchmarks:
| Model Name | Model Download Link | Avg (%) | Model Size (M) |
|---|---|---|---|
| STFPM | Inference Model/Trained Model | 96.2 | 21.5 M |
paddlex --get_pipeline_config anomaly_detection
After execution, the image anomaly detection pipeline configuration file will be saved in the current directory. If you wish to customize the save location, you can execute the following command (assuming the custom save location is ./my_path):
paddlex --get_pipeline_config anomaly_detection --save_path ./my_path
After obtaining the pipeline configuration file, replace --pipeline with the configuration file save path to make the configuration file take effect. For example, if the configuration file save path is ./anomaly_detection.yaml, simply execute:
paddlex --pipeline ./anomaly_detection.yaml --input uad_grid.png --device gpu:0
Here, parameters such as --model and --device do not need to be specified, as they will use the parameters in the configuration file. If parameters are still specified, the specified parameters will take precedence.
The visualized image not saved by default. You can customize the save path through `--save_path`, and then all results will be saved in the specified path.
### 2.2 Python Script Integration
A few lines of code are sufficient for quick inference using the pipeline. Taking the image anomaly detection pipeline as an example:
```python
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="anomaly_detection")
output = pipeline.predict("uad_grid.png")
for res in output:
res.print()
res.save_to_img("./output/")
res.save_to_json("./output/")
```
The results obtained are the same as those from the command line approach.
In the above Python script, the following steps are executed:
(1)Instantiate the `create_pipeline` to create a pipeline object: Specific parameter descriptions are as follows:
| Parameter | Description | Type | Default Value |
|---|---|---|---|
pipeline |
The name of the pipeline or the path to the pipeline configuration file. If it's a pipeline name, it must be a pipeline supported by PaddleX. | str |
None |
device |
The device for pipeline model inference. Supports: "gpu", "cpu". | str |
gpu |
use_hpip |
Whether to enable high-performance inference, only available if the pipeline supports it. | bool |
False |
| Parameter Type | Description |
|---|---|
| Python Var | Supports directly passing Python variables, such as numpy.ndarray representing image data. |
| str | Supports passing the path to the data file to be predicted, such as the local path of an image file: /root/data/img.jpg. |
| str | Supports passing the URL of the data file to be predicted, such as the network URL of an image file: Example. |
| str | Supports passing a local directory, which should contain the data files to be predicted, such as the local path: /root/data/. |
| dict | Supports passing a dictionary type, where the key needs to correspond to the specific task, e.g., "img" for image classification tasks, and the value of the dictionary supports the above data types, for example: {"img": "/root/data1"}. |
| list | Supports passing a list, where the list elements need to be of the above data types, such as [numpy.ndarray, numpy.ndarray], ["/root/data/img1.jpg", "/root/data/img2.jpg"], ["/root/data1", "/root/data2"], [{"img": "/root/data1"}, {"img": "/root/data2/img.jpg"}]. |
| Method | Description | Method Parameters |
|---|---|---|
| Prints results to the terminal | - format_json: bool, whether to format the output content with json indentation, default is True;- indent: int, json formatting setting, only valid when format_json is True, default is 4;- ensure_ascii: bool, json formatting setting, only valid when format_json is True, default is False; |
|
| save_to_json | Saves results as a json file | - save_path: str, the path to save the file, when it's a directory, the saved file name is consistent with the input file type;- indent: int, json formatting setting, default is 4;- ensure_ascii: bool, json formatting setting, default is False; |
| save_to_img | Saves results as an image file | - save_path: str, the path to save the file, when it's a directory, the saved file name is consistent with the input file type; |
For main operations provided by the service:
200, and the response body properties are as follows:| Name | Type | Description |
|---|---|---|
errorCode |
integer |
Error code. Fixed as 0. |
errorMsg |
string |
Error message. Fixed as "Success". |
The response body may also have a result property of type object, which stores the operation result information.
| Name | Type | Description |
|---|---|---|
errorCode |
integer |
Error code. Same as the response status code. |
errorMsg |
string |
Error message. |
Main operations provided by the service:
inferPerforms anomaly detection on images.
POST /image-anomaly-detection
| Name | Type | Description | Required |
|---|---|---|---|
image |
string |
The URL of the image file accessible by the service or the Base64 encoded result of the image file content. | Yes |
result of the response body has the following properties:| Name | Type | Description |
|---|---|---|
labelMap |
array |
Records the class label of each pixel in the image (arranged in row-major order), where 255 represents an anomaly point, and 0 represents a non-anomaly point. |
size |
array |
Image shape. The elements in the array are the height and width of the image in order. |
image |
string |
Anomaly detection result image. The image is in JPEG format and encoded in Base64. |
Example of result:
{
"labelMap": [
0,
0,
255,
0
],
"size": [
2,
2
],
"image": "xxxxxx"
}
import base64
import requests
API_URL = "http://localhost:8080/image-anomaly-detection"
image_path = "./demo.jpg"
output_image_path = "./out.jpg"
with open(image_path, "rb") as file:
image_bytes = file.read()
image_data = base64.b64encode(image_bytes).decode("ascii")
payload = {"image": image_data}
response = requests.post(API_URL, json=payload)
assert response.status_code == 200
result = response.json()["result"]
with open(output_image_path, "wb") as file:
file.write(base64.b64decode(result["image"]))
print(f"Output image saved at {output_image_path}")
#include <iostream>
#include "cpp-httplib/httplib.h" // https://github.com/Huiyicc/cpp-httplib
#include "nlohmann/json.hpp" // https://github.com/nlohmann/json
#include "base64.hpp" // https://github.com/tobiaslocker/base64
int main() {
httplib::Client client("localhost:8080");
const std::string imagePath = "./demo.jpg";
const std::string outputImagePath = "./out.jpg";
httplib::Headers headers = {
{"Content-Type", "application/json"}
};
std::ifstream file(imagePath, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (!file.read(buffer.data(), size)) {
std::cerr << "Error reading file." << std::endl;
return 1;
}
std::string bufferStr(reinterpret_cast<const char*>(buffer.data()), buffer.size());
std::string encodedImage = base64::to_base64(bufferStr);
nlohmann::json jsonObj;
jsonObj["image"] = encodedImage;
std::string body = jsonObj.dump();
auto response = client.Post("/image-anomaly-detection", headers, body, "application/json");
if (response && response->status == 200) {
nlohmann::json jsonResponse = nlohmann::json::parse(response->body);
auto result = jsonResponse["result"];
encodedImage = result["image"];
std::string decodedString = base64::from_base64(encodedImage);
std::vector<unsigned char> decodedImage(decodedString.begin(), decodedString.end());
std::ofstream outputImage(outPutImagePath, std::ios::binary | std::ios::out);
if (outputImage.is_open()) {
outputImage.write(reinterpret_cast<char*>(decodedImage.data()), decodedImage.size());
outputImage.close();
std::cout << "Output image saved at " << outPutImagePath << std::endl;
} else {
std::cerr << "Unable to open file for writing: " << outPutImagePath << std::endl;
}
} else {
std::cout << "Failed to send HTTP request." << std::endl;
return 1;
}
return 0;
}
import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws IOException {
String API_URL = "http://localhost:8080/image-anomaly-detection";
String imagePath = "./demo.jpg";
String outputImagePath = "./out.jpg";
File file = new File(imagePath);
byte[] fileContent = java.nio.file.Files.readAllBytes(file.toPath());
String imageData = Base64.getEncoder().encodeToString(fileContent);
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode params = objectMapper.createObjectNode();
params.put("image", imageData);
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.Companion.get("application/json; charset=utf-8");
RequestBody body = RequestBody.Companion.create(params.toString(), JSON);
Request request = new Request.Builder()
.url(API_URL)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String responseBody = response.body().string();
JsonNode resultNode = objectMapper.readTree(responseBody);
JsonNode result = resultNode.get("result");
String base64Image = result.get("image").asText();
JsonNode labelMap = result.get("labelMap");
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
try (FileOutputStream fos = new FileOutputStream(outputImagePath)) {
fos.write(imageBytes);
}
System.out.println("Output image saved at " + outputImagePath);
} else {
System.err.println("Request failed with code: " + response.code());
}
}
}
}
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
API_URL := "http://localhost:8080/image-anomaly-detection"
imagePath := "./demo.jpg"
outputImagePath := "./out.jpg"
imageBytes, err := ioutil.ReadFile(imagePath)
if err != nil {
fmt.Println("Error reading image file:", err)
return
}
imageData := base64.StdEncoding.EncodeToString(imageBytes)
payload := map[string]string{"image": imageData}
payloadBytes, err := json.Marshal(payload)
if err != nil {
fmt.Println("Error marshaling payload:", err)
return
}
client := &http.Client{}
req, err := http.NewRequest("POST", API_URL, bytes.NewBuffer(payloadBytes))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
type Response struct {
Result struct {
Image string `json:"image"`
Labelmap []map[string]interface{} `json:"labelMap"`
} `json:"result"`
}
var respData Response
err = json.Unmarshal([]byte(string(body)), &respData)
if err != nil {
fmt.Println("Error unmarshaling response body:", err)
return
}
outputImageData, err := base64.StdEncoding.DecodeString(respData.Result.Image)
if err != nil {
fmt.Println("Error decoding base64 image data:", err)
return
}
err = ioutil.WriteFile(outputImagePath, outputImageData, 0644)
if err != nil {
fmt.Println("Error writing image to file:", err)
return
}
fmt.Printf("Image saved at %s.jpg\n", outputImagePath)
}
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
static readonly string API_URL = "http://localhost:8080/image-anomaly-detection";
static readonly string imagePath = "./demo.jpg";
static readonly string outputImagePath = "./out.jpg";
static async Task Main(string[] args)
{
var httpClient = new HttpClient();
byte[] imageBytes = File.ReadAllBytes(imagePath);
string image_data = Convert.ToBase64String(imageBytes);
var payload = new JObject{ { "image", image_data } };
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(API_URL, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
JObject jsonResponse = JObject.Parse(responseBody);
string base64Image = jsonResponse["result"]["image"].ToString();
byte[] outputImageBytes = Convert.FromBase64String(base64Image);
File.WriteAllBytes(outputImagePath, outputImageBytes);
Console.WriteLine($"Output image saved at {outputImagePath}");
}
}
const axios = require('axios');
const fs = require('fs');
const API_URL = 'http://localhost:8080/image-anomaly-detection'
const imagePath = './demo.jpg'
const outputImagePath = "./out.jpg";
let config = {
method: 'POST',
maxBodyLength: Infinity,
url: API_URL,
data: JSON.stringify({
'image': encodeImageToBase64(imagePath)
})
};
function encodeImageToBase64(filePath) {
const bitmap = fs.readFileSync(filePath);
return Buffer.from(bitmap).toString('base64');
}
axios.request(config)
.then((response) => {
const result = response.data["result"];
const imageBuffer = Buffer.from(result["image"], 'base64');
fs.writeFile(outputImagePath, imageBuffer, (err) => {
if (err) throw err;
console.log(`Output image saved at ${outputImagePath}`);
});
})
.catch((error) => {
console.log(error);
});
<?php
$API_URL = "http://localhost:8080/image-anomaly-detection";
$image_path = "./demo.jpg";
$output_image_path = "./out.jpg";
$image_data = base64_encode(file_get_contents($image_path));
$payload = array("image" => $image_data);
$ch = curl_init($API_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true)["result"];
file_put_contents($output_image_path, base64_decode($result["image"]));
echo "Output image saved at " . $output_image_path . "\n";
?>