Guides

Image segmentation with a U-Net: from masks to a trained model

To train a segmentation model, pair every image with a mask that gives each pixel its class (background, road, cell, defect) and train a network whose output keeps the height and width of the image, with one channel per class, such as a U-Net. This guide does that in Brick DNN, first on the built-in Shapes data, then on your own images and masks, and explains how to read the results.

What a segmentation network needs

A classifier gives one answer per image; a segmentation network gives one per pixel. Its output therefore has the height and width of its Input and one channel per class: classes, height, width. The network ends with raw scores, not with Softmax. A U-Net is built for exactly this: an encoder that halves the image to see what is in it, a decoder that brings it back to full size, and skip connections that carry the details across (see the U-Net example for every layer and its shape).

Train it once on built-in data

Before preparing your own data, check the whole path on data that needs no upload:

  1. Open the U-Net example

    Open the U-Net in the editor. Its Input is 3, 64, 64 and its last 1×1 convolution has four output channels.

  2. Choose Shapes

    Press Train and choose Built-in → Shapes: 500 generated images of 64 × 64 pixels with squares, circles and triangles on a noisy background, and a mask for each with four classes. It fits the network as it is.

  3. Start the training

    Keep the batch size of 8 and ten epochs and start. On a CPU this takes a few CPU minutes and reaches about 80 % mean IoU, well within the 15 CPU minutes per run of the free plan.

Prepare your own images and masks

Your data is one ZIP file with a folder images and a folder masks. An image and its mask have the same file name; the mask may also end in _mask, _label, _seg or _gt, and the extension may differ:

images/001.jpg        masks/001.png
images/002.jpg        masks/002_mask.png
classes.txt           (optional: one class name per line)

Folders train/ and val/ (and optionally test/), each with its own images and masks, fix the split; otherwise the pairs are split at random. Images may have any size up to 4096 × 4096 and are resized to the Input; masks are resized with nearest neighbour, so no classes are mixed.

How a mask is read is decided once for the whole dataset:

Mask formats that Brick DNN reads
MasksRead as
Only black (0) and white (255)Two classes: background and foreground
Grey values or palette indices below 32The class of each pixel (0, 1, 2 …); 255 marks pixels to ignore
At most 32 other grey values, e.g. 0, 128, 255Classes in ascending order
Colour masks with at most 32 coloursOne class per colour (order from classes.json, or black first)

Save masks as PNG without smoothing. JPEG compression and anti-aliased edges create in-between values, and such masks are refused at upload with the reason.

Fit the network to your data

When you choose your dataset, Brick DNN sets the Input shape and the out_channels of the last convolution to the number of classes, and says what it changed. Two things to keep in mind:

  • Every pooling layer halves height and width, so with three of them both must be divisible by 8. The check explains it if the output ends up smaller than the Input.
  • Larger inputs cost more: CPU time grows with the number of pixels. Start at 64 × 64 or 128 × 128 and go up once the network learns; the Input can be at most 512 × 512.

Batch size and loss

Every layer keeps its output for every pixel of a batch, so batches are much smaller than for classification: 4 to 16 is usual. A batch that would not fit into memory is refused before the start, with the batch size that fits.

The default loss is the cross-entropy of every pixel. When one class covers only a few pixels (a thin crack, a small cell), choose Cross-entropy + Dice, which adds the Dice score of the predicted probabilities, or the weighted cross-entropy with balanced class weights from the pixel counts. The check suggests them when one class has more than 97 % of the pixels.

Read the results

After every epoch Brick DNN measures three numbers on the validation images:

  • Mean IoU, for each class the overlap of predicted and true pixels divided by their union, averaged over the classes. It is the headline number.
  • Dice, twice the overlap divided by the sum of both, averaged the same way; always at least the IoU.
  • Pixel accuracy, the share of pixels with the right class. With a lot of background it is high even for a poor network, so do not judge by it alone.

The run view adds the IoU of every class for the kept weights and shows predictions for eight validation images: the image, the true mask, the predicted mask and an overlay.

Predictions of a U-Net trained on the Shapes data: for each validation image the image, the true mask, the predicted mask and an overlay, with IoU and pixel accuracy.
Predicted masks next to the true ones, with the IoU of each image.

Use the trained model

Predict a new image on the server with the REST API or the MCP tool predict: it is converted and resized like the training images, and the answer contains the share of each class and the class map as a small PNG whose pixel values are the class indices. Or download the weights and the script and run it yourself; output.argmax(dim=1) gives the class of every pixel. The details are in training.md.

Examples to start from

  • U-Net for segmentation

    Encoder, decoder and skip connections: a class for every pixel, trained on the built-in Shapes data.

    PyTorch · 1,925,700 parameters

  • U-Net classifier

    The U-Net architecture with a classification head: global pooling and a Linear layer give ten class scores.

    PyTorch · 481,898 parameters

  • Residual CNN for CIFAR-10

    A ResNet-style block with a skip connection merged by Add, then global average pooling.

    PyTorch · 76,490 parameters

More guides

Open the editor