Main Content

balancePixelLabels

Balance pixel labels by oversampling block locations in large images

Description

example

blockLocations = balancePixelLabels(blockedImages,blockSize,numObservations) creates a list of block locations in the large labeled images, blockedImages, that result in a class balanced data set by oversampling image regions that contain less-common labels. numObservations is the required number of block locations, and blockSize specifies the block size.

A balanced dataset can produce better results when used for training workflows such as semantic segmentation in deep learning.

blockLocations = balancePixelLabels(blockedImages,blockSize,numObservations,Name,Value) specifies additional aspects of the selected blocks using name-value arguments.

Examples

collapse all

Specify the location of a labeled image dataset.

dataDir = fullfile(toolboxdir('vision'), 'visiondata');
labelDir = fullfile(dataDir, 'buildingPixelLabels');
fileSet = matlab.io.datastore.FileSet(labelDir, "FileExtensions", {'.png'});

Create an array of labeled images from the dataset.

blockedImages = blockedImage(fileSet);

Set block size of the images. Assume finest resolution level.

blockSize = [20 15];

Create a blockedImageDatastore from the image array.

blabelds = blockedImageDatastore(blockedImages, 'BlockSize', blockSize);

Count pixel label occurrences of each class. The classes in the pixel label images are not balanced.

pixelLabelID = [1 2 3 4];
classNames = ["sky" "grass" "building" "sidewalk"];
labelCounts = countEachLabel(blabelds,...
                 'Classes', classNames, 'PixelLabelIDs', pixelLabelID);

Speciy number of block locations to sample from the dataset.

numObservations = 2000;

Select block locations from the labeled images to achieve class.

locationSet = balancePixelLabels(blockedImages, blockSize, numObservations,...
                 'Classes', classNames, 'PixelLabelIDs', pixelLabelID);

Create a blockedImageDatastore using the block locations after balancing.

blabeldsBalanced = blockedImageDatastore(blockedImages, 'BlockLocationSet', locationSet);

Recalculate the pixel label occurrences for the balanced dataset.

labelCountsBalanced = countEachLabel(blabeldsBalanced,...
                     'Classes', classNames, 'PixelLabelIDs', pixelLabelID);

Compare the original unbalanced labels and labels after label balancing.

figure
h1 = histogram('Categories',labelCounts.Name,...
    'BinCounts',labelCounts.PixelCount)
h1 = 
  Histogram with properties:

              Data: [0x0 categorical]
            Values: [314849 159787 1031235 25313]
    NumDisplayBins: 4
        Categories: {'sky'  'grass'  'building'  'sidewalk'}
      DisplayOrder: 'manual'
     Normalization: 'count'
      DisplayStyle: 'bar'
         FaceColor: 'auto'
         EdgeColor: [0 0 0]

  Show all properties

title(h1.Parent,'Original dataset labels')

Figure contains an axes object. The axes object with title Original dataset labels contains an object of type categoricalhistogram.

figure
h2 = histogram('Categories',labelCountsBalanced.Name,...
    'BinCounts',labelCountsBalanced.PixelCount)
h2 = 
  Histogram with properties:

              Data: [0x0 categorical]
            Values: [131906 241546 81006 143167]
    NumDisplayBins: 4
        Categories: {'sky'  'grass'  'building'  'sidewalk'}
      DisplayOrder: 'manual'
     Normalization: 'count'
      DisplayStyle: 'bar'
         FaceColor: 'auto'
         EdgeColor: [0 0 0]

  Show all properties

title(h2.Parent,'Balanced dataset labels')

Figure contains an axes object. The axes object with title Balanced dataset labels contains an object of type categoricalhistogram.

Input Arguments

collapse all

Labeled blocked images, specified as a blockedImage object or a vector of blockedImage objects containing pixel label images.

Block size of read data, specified as a two-element row vector of positive integers, [numrows,numcols]. The first element specifies the number of rows in the block. The second element specifies the number of columns.

Number of block locations to return, specified as a positive integer.

Name-Value Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: 'Classes',classNames,'PixelLabelIDs',pixelLabelID

Image resolution levels, specified as a numeric scalar or an integer-valued vector of the same length as the vector of blockedImages. If you specify a scalar value, then all blocked images supply blocks at the specified resolution level.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Set of class names, specified as a string vector or a cell array of character vectors.

You must specify this argument when blockedImages yields numeric data, such as when pixel label data is stored as an RGB image. Do not specify this argument when blockedImages yields categorical data.

Data Types: char | string

Numeric IDs that map labels to class names, specified as a vector of numeric IDs for each label or an M-by-3 matrix where M is the number of class names. The length of the vector must equal the number of class names. Each row is a three-element vector representing the RGB pixel value associated with each class name.

You must specify this argument when blockedImages yields numeric data, such as when pixel label data is stored as an RGB image. Do not specify this argument when blockedImages yields categorical data.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Use a new or existing parallel pool, specified as a numeric or logical 1 (true) or 0 (false). If no parallel pool is active, then a new pool is opened based on the default parallel settings. The DataSource property of all input blockedImage objects should be valid paths on each of the parallel workers.

This syntax requires the Parallel Computing Toolbox™.

Data Types: logical

Output Arguments

collapse all

Block locations, returned as a blockLocationSet object. The object contains numObservations number of locations of balanced blocks, each of size blockSize.

Algorithms

To balance pixel labels, the function oversamples the minority classes in the input images. The minority class is determined by calculating the overall pixel label counts for the complete dataset. The algorithm follows these steps.

  1. The images in the input image array are divided into macro blocks, which is a multiple of the blockSize input value.

  2. The function counts pixel labels for all classes in each macro block. Then, it selects the macro block with the greatest occurrences of minority classes using weighted random selection.

  3. The algorithm uses a random block location within the selected macro block to perform oversampling. The origin of the block location must always be fully within the limits of the macro block.

  4. The function updates the overall label counts based on the pixel label counts of the classes found for the selected macro block.

  5. The function includes the new (oversampled) classes to compute new minority class.

  6. This process repeats until the number of block locations processed equals the value specified by the numObservations input value.

Compatibility Considerations

expand all

Not recommended starting in R2021a

Introduced in R2020a