---
comments: true
---
# General Semantic Segmentation Pipeline Tutorial
## 1. Introduction to the General Semantic Segmentation Pipeline
Semantic segmentation is a computer vision technique that aims to assign each pixel in an image to a specific category, enabling a detailed understanding of the image content. Semantic segmentation not only identifies the types of objects in an image but also classifies each pixel, allowing regions of the same category to be fully labeled. For example, in a street scene image, semantic segmentation can distinguish pedestrians, cars, the sky, and roads pixel by pixel, forming a detailed label map. This technology is widely used in autonomous driving, medical image analysis, and human-computer interaction, often relying on deep learning models (such as SegFormer, etc.) to extract features by CNN or Transformer, and achieve high-precision pixel-level classification, providing a foundation for further intelligent analysis.
| Model Name | Model Download Link | mIoU (%) | GPU Inference Time (ms) [Normal Mode / High-Performance Mode] |
CPU Inference Time (ms) [Normal Mode / High-Performance Mode] |
Model Size (M) |
|---|---|---|---|---|---|
| OCRNet_HRNet-W48 | Inference Model/Training Model | 82.15 | 627.36 / 170.76 | 3531.61 / 3531.61 | 249.8 M |
| PP-LiteSeg-T | Inference Model/Training Model | 73.10 | 30.16 / 14.03 | 420.07 / 235.01 | 28.5 M |
| Model Name | Model Download Link | mIoU (%) | GPU Inference Time (ms) [Normal Mode / High-Performance Mode] |
CPU Inference Time (ms) [Normal Mode / High-Performance Mode] |
Model Size (M) |
|---|---|---|---|---|---|
| Deeplabv3_Plus-R50 | Inference Model/Training Model | 80.36 | 503.51 / 122.30 | 3543.91 / 3543.91 | 94.9 M |
| Deeplabv3_Plus-R101 | Inference Model/Training Model | 81.10 | 803.79 / 175.45 | 5136.21 / 5136.21 | 162.5 M |
| Deeplabv3-R50 | Inference Model/Training Model | 79.90 | 647.56 / 121.67 | 3803.09 / 3803.09 | 138.3 M |
| Deeplabv3-R101 | Inference Model/Training Model | 80.85 | 950.43 / 178.50 | 5517.14 / 5517.14 | 205.9 M |
| OCRNet_HRNet-W18 | Inference Model/Training Model | 80.67 | 286.12 / 80.76 | 1794.03 / 1794.03 | 43.1 M |
| OCRNet_HRNet-W48 | Inference Model/Training Model | 82.15 | 627.36 / 170.76 | 3531.61 / 3531.61 | 249.8 M |
| PP-LiteSeg-T | Inference Model/Training Model | 73.10 | 30.16 / 14.03 | 420.07 / 235.01 | 28.5 M |
| PP-LiteSeg-B | Inference Model/Training Model | 75.25 | 40.92 / 20.18 | 494.32 / 310.34 | 47.0 M |
| SegFormer-B0 (slice) | Inference Model/Training Model | 76.73 | 11.1946 | 268.929 | 13.2 M |
| SegFormer-B1 (slice) | Inference Model/Training Model | 78.35 | 17.9998 | 403.393 | 48.5 M |
| SegFormer-B2 (slice) | Inference Model/Training Model | 81.60 | 48.0371 | 1248.52 | 96.9 M |
| SegFormer-B3 (slice) | Inference Model/Training Model | 82.47 | 64.341 | 1666.35 | 167.3 M |
| SegFormer-B4 (slice) | Inference Model/Training Model | 82.38 | 82.4336 | 1995.42 | 226.7 M |
| SegFormer-B5 (slice) | Inference Model/Training Model | 82.58 | 97.3717 | 2420.19 | 229.7 M |
The accuracy metrics of the above models are measured on the Cityscapes dataset. GPU inference time is based on an NVIDIA Tesla T4 machine with FP32 precision. CPU inference speed is based on an Intel(R) Xeon(R) Gold 5117 CPU @ 2.00GHz with 8 threads and FP32 precision.
| Model Name | Model Download Link | mIoU (%) | GPU Inference Time (ms) [Normal Mode / High-Performance Mode] |
CPU Inference Time (ms) [Normal Mode / High-Performance Mode] |
Model Size (M) |
|---|---|---|---|---|---|
| SeaFormer_base(slice) | Inference Model/Training Model | 40.92 | 24.4073 | 397.574 | 30.8 M |
| SeaFormer_large (slice) | Inference Model/Training Model | 43.66 | 27.8123 | 550.464 | 49.8 M |
| SeaFormer_small (slice) | Inference Model/Training Model | 38.73 | 19.2295 | 358.343 | 14.3 M |
| SeaFormer_tiny (slice) | Inference Model/Training Model | 34.58 | 13.9496 | 330.132 | 6.1M |
| Mode | GPU Configuration | CPU Configuration | Acceleration Technology Combination |
|---|---|---|---|
| Normal Mode | FP32 Precision / No TRT Acceleration | FP32 Precision / 8 Threads | PaddleInference |
| High-Performance Mode | Optimal combination of pre-selected precision types and acceleration strategies | FP32 Precision / 8 Threads | Pre-selected optimal backend (Paddle/OpenVINO/TRT, etc.) |
If you are satisfied with the pipeline's performance, you can directly integrate and deploy it. If not, you can also use your private data to fine-tune the model in the pipeline online.
### 2.2 Local Experience
> ❗ Before using the general semantic segmentation pipeline locally, please ensure that you have completed the installation of the PaddleX wheel package according to the [PaddleX Local Installation Guide](../../../installation/installation.en.md).
#### 2.2.1 Command Line Experience
* You can quickly experience the semantic segmentation pipeline effect with a single command. Use the [test file](https://paddle-model-ecology.bj.bcebos.com/paddlex/PaddleX3.0/application/semantic_segmentation/makassaridn-road_demo.png), and replace `--input` with the local path for prediction.
```bash
paddlex --pipeline semantic_segmentation \
--input makassaridn-road_demo.png \
--target_size -1 \
--save_path ./output \
--device gpu:0 \
```
The relevant parameter descriptions can be referred to in the parameter explanations in [2.2.2 Python Script Integration]().
After running, the result will be printed to the terminal, as follows:
```bash
{'res': {'input_path': 'makassaridn-road_demo.png', 'page_index': None, 'pred': '...'}}
```
The explanation of the output result parameters can be found in the [2.2.2 Integration with Python Script](#222-integration-with-python-script) section.
The visualization results are saved under `save_path`, and the visualization result of semantic segmentation is as follows:
#### 2.2.2 Integration with Python Script
* The above command line is for quickly experiencing and viewing the effect. Generally, in a project, it is often necessary to integrate through code. You can complete the fast inference of the pipeline with just a few lines of code. The inference code is as follows:
```python
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="semantic_segmentation")
output = pipeline.predict(input="makassaridn-road_demo.png", target_size = -1)
for res in output:
res.print()
res.save_to_img(save_path="./output/")
res.save_to_json(save_path="./output/")
```
In the above Python script, the following steps are executed:
(1) The semantic segmentation pipeline object is instantiated via `create_pipeline()`, with the following parameter descriptions:
| Parameter | Description | Type | Default |
|---|---|---|---|
pipeline |
Pipeline name or path to pipeline config file, if it's set as a pipeline name, it must be a pipeline supported by PaddleX. | str |
None |
config |
Specific configuration information for the pipeline (if set simultaneously with the pipeline, it takes precedence over the pipeline, and the pipeline name must match the pipeline).
|
dict[str, Any] |
None |
device |
Pipeline inference device. Supports specifying the specific GPU card number, such as "gpu:0", other hardware specific card numbers, such as "npu:0", CPU such as "cpu". | str |
None |
use_hpip |
Whether to enable high-performance inference, only available when the pipeline supports high-performance inference. | bool |
False |
| Parameter | Description | Type | Options | Default Value |
|---|---|---|---|---|
input |
Data to be predicted, supports multiple input types, required | Python Var|str|list |
|
None |
device |
Pipeline inference device | str|None |
|
None |
target_size |
Image resolution actually used during model inference | int|-1|None|tuple[int,int] |
|
None |
| Method | Description | Parameter | Type | Explanation | Default Value |
|---|---|---|---|---|---|
print() |
Print the result to the terminal | format_json |
bool |
Whether to format the output content using JSON indentation |
True |
indent |
int |
Specify the indentation level to beautify the JSON data for better readability. This is only effective when format_json is True |
4 | ||
ensure_ascii |
bool |
Control whether non-ASCII characters are escaped to Unicode. If set to True, all non-ASCII characters will be escaped; False retains the original characters. This is only effective when format_json is True |
False |
||
save_to_json() |
Save the result as a JSON file | save_path |
str |
The file path for saving. If it is a directory, the saved file will have the same name as the input file type | None |
indent |
int |
Specify the indentation level to beautify the JSON data for better readability. This is only effective when format_json is True |
4 | ||
ensure_ascii |
bool |
Control whether non-ASCII characters are escaped to Unicode. If set to True, all non-ASCII characters will be escaped; False retains the original characters. This is only effective when format_json is True |
False |
||
save_to_img() |
Save the result as an image file | save_path |
str |
The file path for saving, supporting both directory and file paths | None |
| Attribute | Attribute Description |
|---|---|
json |
Get the prediction results in json format |
img |
Get the visualization image in dict format |
For the main operations provided by the service:
200, and the attributes of the response body are as follows:| Name | Type | Meaning |
|---|---|---|
logId |
string |
The UUID of the request. |
errorCode |
integer |
Error code. Fixed at 0. |
errorMsg |
string |
Error description. Fixed at "Success". |
result |
object |
Operation result. |
| Name | Type | Meaning |
|---|---|---|
logId |
string |
The UUID of the request. |
errorCode |
integer |
Error code. Same as the response status code. |
errorMsg |
string |
Error description. |
The main operations provided by the service are as follows:
inferPerform semantic segmentation on an image.
POST /semantic-segmentation
| Name | Type | Meaning | Required |
|---|---|---|---|
image |
string |
The URL of the image file accessible by the server or the Base64 encoded content of the image file. | Yes |
targetSize |
integer | array | null |
Please refer to the description of the target_size parameter of the pipeline object's predict method. |
No |
result of the response body has the following attributes:| Name | Type | Meaning |
|---|---|---|
labelMap |
array |
Records the class label of each pixel in the image (arranged in row-major order). |
size |
array |
Image shape. The elements in the array are the height and width of the image, respectively. |
image |
string| null |
Semantic segmentation result image. The image is in JPEG format and encoded using Base64. |
An example of result is as follows:
{
"labelMap": [
0,
0,
1,
2
],
"size": [
2,
2
],
"image": "xxxxxx"
}
import base64
import requests
API_URL = "http://localhost:8080/semantic-segmentation" # Service URL
image_path = "./demo.jpg"
output_image_path = "./out.jpg"
# Base64 encode the local image
with open(image_path, "rb") as file:
image_bytes = file.read()
image_data = base64.b64encode(image_bytes).decode("ascii")
payload = {"image": image_data} # Base64 encoded file content or image URL
# Call the API
response = requests.post(API_URL, json=payload)
# Handle the API response
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}")
# result.labelMap records the category label of each pixel in the image (in row-major order) see API reference documentation for details
#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"}
};
// Base64 encode the local image
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();
// Call the API
auto response = client.Post("/semantic-segmentation", headers, body, "application/json");
// Handle the API response
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;
// result.labelMap records the category label of each pixel in the image (in row-major order) see API reference documentation for details
} 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/semantic-segmentation"; // Service URL
String imagePath = "./demo.jpg"; // Local image
String outputImagePath = "./out.jpg"; // Output image
// Encode the local image using Base64
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); // Base64 encoded file content or image URL
// Create an OkHttpClient instance
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();
// Call the API and process the response data
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);
// result.labelMap records the class labels of each pixel in the image (arranged in row-major order), see the API reference documentation for details
} 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/semantic-segmentation"
imagePath := "./demo.jpg"
outputImagePath := "./out.jpg"
// Encode the local image to Base64
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} // Base64-encoded file content or image URL
payloadBytes, err := json.Marshal(payload)
if err != nil {
fmt.Println("Error marshaling payload:", err)
return
}
// Call the API
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()
// Process the response data
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)
// result.labelMap records the class labels of each pixel in the image (arranged in row-major order). See the API reference for details.
}
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/semantic-segmentation";
static readonly string imagePath = "./demo.jpg";
static readonly string outputImagePath = "./out.jpg";
static async Task Main(string[] args)
{
var httpClient = new HttpClient();
// Encode the local image in Base64
byte[] imageBytes = File.ReadAllBytes(imagePath);
string image_data = Convert.ToBase64String(imageBytes);
var payload = new JObject{ { "image", image_data } }; // Base64 encoded file content or image URL
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
// Call the API
HttpResponseMessage response = await httpClient.PostAsync(API_URL, content);
response.EnsureSuccessStatusCode();
// Process the returned data
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}");
// result.labelMap records the class label of each pixel in the image (arranged in row-major order). See the API reference documentation for details.
}
}
const axios = require('axios');
const fs = require('fs');
const API_URL = 'http://localhost:8080/semantic-segmentation'
const imagePath = './demo.jpg'
const outputImagePath = "./out.jpg";
let config = {
method: 'POST',
maxBodyLength: Infinity,
url: API_URL,
data: JSON.stringify({
'image': encodeImageToBase64(imagePath) // Base64 encoded file content or image URL
})
};
// Base64 encode the local image
function encodeImageToBase64(filePath) {
const bitmap = fs.readFileSync(filePath);
return Buffer.from(bitmap).toString('base64');
}
// Call the API
axios.request(config)
.then((response) => {
// Handle the API 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}`);
});
// result.labelMap records the category label of each pixel in the image (in row-major order) see API reference documentation for details
})
.catch((error) => {
console.log(error);
});
<?php
$API_URL = "http://localhost:8080/semantic-segmentation"; // Service URL
$image_path = "./demo.jpg";
$output_image_path = "./out.jpg";
// Encode the local image using Base64
$image_data = base64_encode(file_get_contents($image_path));
$payload = array("image" => $image_data); // Base64 encoded file content or image URL
// Call the API
$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);
// Process the response data
$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";
// result.labelMap records the class labels of each pixel in the image (arranged in row-major order), see the API reference documentation for details
?>
| Scenario | Fine-Tuning Module | Reference Link |
|---|---|---|
| Prediction results are not satisfactory | Semantic Segmentation Module | Link |