Class OpenCVTools

java.lang.Object
qupath.opencv.tools.OpenCVTools

public class OpenCVTools extends Object
Collection of static methods to help with using OpenCV from Java.
Author:
Pete Bankhead
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static class 
    Class representing the indices of a pixel and its value.
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    static void
    addNoise(Mat mat, double mean, double stdDev)
    Add Gaussian noise with specified mean and standard deviation to all channels of a Mat.
    static void
    apply(Mat mat, DoubleUnaryOperator operator)
    Apply an operation to the pixels of an image.
    static Mat
    applyTiled(Function<Mat,Mat> fun, Mat mat, int tileWidth, int tileHeight, Padding padding, int borderType)
    Apply a function to a Mat that strictly requires a specific input size.
    static void
    Apply a method that modifies a Mat in-place to all channels of the Mat, merging the result and storing the result in-place.
    static void
    ceil(Mat mat)
    Ceil values in a floating point Mat.
    static double[]
    Get the minimum of an image channel, ignoring NaNs.
    static double[]
    Get the mean of an image channel, ignoring NaNs.
    static double[]
    Get the minimum of an image channel, ignoring NaNs.
    static double[]
    Get the standard deviation of image channels, ignoring NaNs.
    static double[]
    Get the sum of image channels, ignoring NaNs.
    static void
    closingFilter(Mat mat, int radius)
    Apply a 2D closing filter (dilation followed by erosion) to all channels of an image.
    createAnnotations(Mat matLabels, RegionRequest region, int minLabel, int maxLabel)
    Create annotation objects by tracing contours in a labelled image.
    static Mat
    Create a binary mask (0, 255 values) by applying a predicate to pixel values.
    createCells(Mat matLabelsNuclei, Mat matLabelsCells, RegionRequest region, int minLabel, int maxLabel)
    Create cell objects by tracing contours in a labelled image.
    createDetections(Mat matLabels, RegionRequest region, int minLabel, int maxLabel)
    Create detection objects by tracing contours in a labelled image.
    static Mat
    createDisk(int radius, boolean doMean)
    Create a disk filter.
    static Mat
    createMask(Mat mat, DoublePredicate predicate, double trueValue, double falseValue)
    Create a mask by applying a predicate to pixel values.
    createObjects(Mat matLabels, RegionRequest region, int minLabel, int maxLabel, BiFunction<ROI,Number,PathObject> creator)
    Create objects by tracing contours in a labelled image.
    static Map<Number,ROI>
    createROIs(Mat matLabels, RegionRequest region, int minLabel, int maxLabel)
    Convert integer labels into ROIs.
    static Mat
    crop(Mat mat, int x, int y, int width, int height)
    Crop a region from a Mat based on its bounding box, returning a new image (not a subregion).
    static Mat
    crop(Mat mat, Padding padding)
    Crop a region from a Mat by stripping off padding, returning a new image (not a subregion).
    static Mat
    ensureContinuous(Mat mat, boolean inPlace)
    Ensure a Mat is continuous, creating a copy of the data if necessary.
    static double[]
    Extract pixels as a double array.
    static float[]
    Extract pixels as a float array.
    static double[]
    extractMaskedDoubles(Mat input, Mat mask, int channel)
    Extract pixels from an image using a mask, limited to the specified channel index.
    static float[]
    extractMaskedFloats(Mat input, Mat mask, int channel)
    Extract pixels from an image using a mask, limited to the specified channel index.
    static double[]
    extractPixels(Mat mat, double[] pixels)
    Extract pixels as a double array.
    static float[]
    extractPixels(Mat mat, float[] pixels)
    Extract pixels as a float[] array.
    static List<Mat>
    Extract a list of Mats, where each Mat corresponds to a z-slice, for all available z-slices of a region.
    static List<Mat>
    extractZStack(ImageServer<BufferedImage> server, RegionRequest request, int zMin, int zMax)
    Extract a list of Mats, where each Mat corresponds to a z-slice.
    static void
    fill(Mat mat, double value)
    Fill the pixels of an image with a specific value.
    static void
    fill(Mat mat, Mat mask, double value)
    Fill the pixels of an image with a specific value, corresponding to a mask.
    static void
    fillSmallHoles(Mat matBinary, double maxArea)
    Fill holes in a binary image (1-channel, 8-bit unsigned) with an area <= maxArea.
    static void
    filter2D(Mat mat, Mat kernel)
    Apply a 2D filter to all channels of an image, with symmetric boundary padding.
    static void
    filter2D(Mat mat, Mat kernel, int borderType)
    Apply a 2D filter to all channels of an image.
    static Mat
    filterSingleZ(List<Mat> mats, double[] kernel, int ind3D, int border)
    Apply a filter along the 'list' dimension for a list of Mats, computing the value for a single entry.
    static List<Mat>
    filterZ(List<Mat> mats, Mat kernelZ, int ind3D, int border)
    Filter filter along entries in the input list.
    findMaxima(Mat mat, Mat mask)
    Find maxima within an image.
    static Mat
    Get the regional maxima within a Mat, providing the output as a labeled image.
    static void
    floor(Mat mat)
    Floor values in a floating point Mat.
    static void
    gaussianFilter(Mat mat, double sigma)
    Apply a 2D Gaussian filter to all channels of an image, with symmetric boundary padding.
    static void
    gaussianFilter(Mat mat, double sigma, int borderType)
    Apply a 2D Gaussian filter to all channels of an image.
    static Mat
    Deprecated.
    createDisk(int, boolean) gives more reliable shapes.
    static double[]
    getGaussianDeriv(double sigma, int order, int length)
    Get filter coefficients for a 1D Gaussian (derivative) kernel.
    static Mat
    getGaussianDerivKernel(double sigma, int order, boolean doColumn)
    Get filter coefficients for a 1D Gaussian (derivative) kernel.
    getMaskedPixels(Mat mat, Mat mask)
    Extract all the masked pixels within an image.
    static int
    Get the OpenCV type code corresponding to a PixelType.
    static Mat
    hConcat(Collection<? extends Mat> mats, Mat dest)
    Horizontal concatenation for a Mat.
    static Mat
    Convert a BufferedImage to an OpenCV Mat.
    static Mat
    imageToMatBGR(BufferedImage img, boolean includeAlpha)
    Extract 8-bit unsigned pixels from a BufferedImage as a multichannel BGR(A) Mat.
    static Mat
    imageToMatRGB(BufferedImage img, boolean includeAlpha)
    Extract 8-bit unsigned pixels from a BufferedImage as a multichannel RGB(A) Mat.
    static void
    invertBinary(Mat matBinary, Mat matDest)
    Invert a binary image.
    static boolean
    isFloat(Mat mat)
    Returns true if a Mat is a floating point (rather than int) type.
    static Mat
    label(Mat matBinary, int connectivity)
    Label connected components for non-zero pixels in an image.
    static int
    label(Mat matBinary, Mat matLabels, int connectivity)
    Label connected components for non-zero pixels in an image.
    static void
    labelImage(Mat matBinary, Mat matLabels, int contourRetrievalMode)
    Deprecated.
    Convert a Mat to a BufferedImage.
    matToBufferedImage(Mat mat, ColorModel colorModel)
    Convert a Mat to a BufferedImage.
    static ImagePlus
    matToImagePlus(String title, Mat... mats)
    Convert an OpenCV MatVector into an ImageJ ImagePlus.
    static ImagePlus
    matToImagePlus(Mat mat, String title)
    Convert an OpenCV Mat into an ImageJ ImagePlus.
    Convert a single-channel OpenCV Mat into an ImageJ ImageProcessor.
    matToSimpleImage(Mat mat, int channel)
    Convert a Mat to a SimpleImage.
    static double
    maximum(Mat mat)
    Get the maximum value in an image, across all pixels (regardless of channels), ignoring NaNs.
    static void
    maximumFilter(Mat mat, int radius)
    Apply a 2D maximum filter (dilation) to all channels of an image.
    static double
    mean(Mat mat)
    Get the mean of an image, across all pixels (regardless of channels), ignoring NaNs.
    static void
    meanFilter(Mat mat, int radius)
    Apply a circular 2D mean filter to all channels of an image, with symmetric boundary padding.
    static void
    meanFilter(Mat mat, int radius, int borderType)
    Apply a circular 2D mean filter to all channels of an image.
    static double
    median(Mat mat)
    Get the median pixel value in a Mat, ignoring NaNs.
    static String
    Create a brief report on memory use, based on JavaCPP's Pointer class.
    static Mat
    mergeChannels(Collection<? extends Mat> channels, Mat dest)
    Merge channels from a multichannel Mat.
    static double
    minimum(Mat mat)
    Get the minimum value in an image, across all pixels (regardless of channels), ignoring NaNs.
    static void
    minimumFilter(Mat mat, int radius)
    Apply a 2D minimum filter (erosion) to all channels of an image.
    static void
    openingFilter(Mat mat, int radius)
    Apply a 2D opening filter (erosion followed by dilation) to all channels of an image.
    static double[]
    percentiles(Mat mat, double... percentiles)
    Get percentile values for all pixels in a Mat, ignoring NaNs.
    static String
    Get a brief, one-line report on current physical memory use, based on JavaCPP's Pointer class.
    static void
    putPixelsFloat(Mat mat, float[] pixels)
    Set pixels from a float array.
    static void
    putPixelsUnsigned(Mat mat, byte[] pixels)
    Set pixels from a byte array.
    static void
    replaceNaNs(Mat mat, double newValue)
    Replace NaNs in a floating point array.
    static void
    replaceValues(Mat mat, double originalValue, double newValue)
    Replace a specific value in an array.
    static void
    round(Mat mat)
    Round values in a floating point Mat.
    static Mat
    scalarMat(double value, int depth)
    Create a 1x1 single-channel Mat with a specific value.
    static Mat
    scalarMatWithType(double value, int type)
    Create a 1x1 Mat with a specific value, with 1 or more channels.
    static void
    sepFilter2D(Mat mat, Mat kx, Mat ky)
    Apply a separable filter to an image, with symmetric boundary padding.
    static void
    sepFilter2D(Mat mat, Mat kx, Mat ky, int borderType)
    Apply a separable filter to an image.
    static Mat
    Shrink labels to a single point.
    static List<Mat>
    Split channels from a Mat.
    static double
    stdDev(Mat mat)
    Get the standard deviation of an image, across all pixels (regardless of channels), ignoring NaNs.
    static void
    stdDevFilter(Mat mat, int radius)
    Apply a circular 2D local standard deviation filter to all channels of an image, with symmetric boundary padding.
    static void
    stdDevFilter(Mat mat, int radius, int borderType)
    Apply a circular 2D local standard deviation filter to all channels of an image.
    static double
    sum(Mat mat)
    Get the sum of an image, across all pixels (regardless of channels), ignoring NaNs.
    static void
    sumFilter(Mat mat, int radius)
    Apply a circular 2D sum filter to all channels of an image, with symmetric boundary padding.
    static void
    sumFilter(Mat mat, int radius, int borderType)
    Apply a circular 2D sum filter to all channels of an image.
    static String
    Get a brief, one-line report on tracked memory use, based on JavaCPP's Pointer class.
    static int
    typeToChannels(int type)
    Determine the number of channels from a specified Mat type (which also encodes depth).
    static int
    typeToDepth(int type)
    Determine the depth from a specified Mat type (which may also encode the number of channels).
    static void
    varianceFilter(Mat mat, int radius)
    Apply a circular 2D local variance filter to all channels of an image, with symmetric boundary padding.
    static void
    varianceFilter(Mat mat, int radius, int borderType)
    Apply a circular 2D local variance filter to all channels of an image.
    static Mat
    vConcat(Collection<? extends Mat> mats, Mat dest)
    Vertical concatenation for a Mat.
    static void
    watershedIntensitySplit(Mat matBinary, Mat matWatershedIntensities, double threshold, int maximaRadius)
    Apply a watershed transform to refine a binary image, guided either by a distance transform or a supplied intensity image.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • OpenCVTools

      public OpenCVTools()
  • Method Details

    • imageToMat

      public static Mat imageToMat(BufferedImage img)
      Convert a BufferedImage to an OpenCV Mat.

      An effort will be made to do a sensible conversion based on the BufferedImage type, returning a Mat with a suitable type.

      BGR and RGB images will remain with the same channel order, and an alpha channel (if present) will be included at the end (i.e. to give BGRA or RGBA).

      Note: the behavior of this method has changed; in QuPath <= 0.1.2 only RGB images were really supported, and an RGB conversion was *always* made.

      Parameters:
      img -
      Returns:
      See Also:
    • getOpenCVPixelType

      public static int getOpenCVPixelType(PixelType pixelType) throws IllegalArgumentException
      Get the OpenCV type code corresponding to a PixelType.

      Note, OpenCV has no matching type for PixelType.UINT32. In this case a signed 32-bit int type will be returned, and a warning logged.

      Parameters:
      pixelType - the QuPath pixel type
      Returns:
      the closest OpenCV pixel type
      Throws:
      IllegalArgumentException - if the PixelType is unknown
    • apply

      public static void apply(Mat mat, DoubleUnaryOperator operator)
      Apply an operation to the pixels of an image.

      No type conversion is applied; it is recommended to use floating point images, or otherwise check that clipping, rounding and non-finite values are handled as expected.

      Parameters:
      mat - image
      operator - operator to apply to pixels of the image, in-place
    • createMask

      public static Mat createMask(Mat mat, DoublePredicate predicate, double trueValue, double falseValue)
      Create a mask by applying a predicate to pixel values.
      Parameters:
      mat - the input image
      predicate - the predicate to apply to each pixel
      trueValue - the value to include in the mask for pixels that match the predicate
      falseValue - the value to include in the mask for pixels that do not match the predicate
      Returns:
      the mask
      See Also:
    • createBinaryMask

      public static Mat createBinaryMask(Mat mat, DoublePredicate predicate)
      Create a binary mask (0, 255 values) by applying a predicate to pixel values.
      Parameters:
      mat - the input image
      predicate - the predicate to apply to each pixel
      Returns:
      the mask
      See Also:
    • replaceValues

      public static void replaceValues(Mat mat, double originalValue, double newValue)
      Replace a specific value in an array.

      If the value to replace is NaN, use instead replaceNaNs(Mat, double).

      Parameters:
      mat - array
      originalValue - value to replace
      newValue - value to include in the output
      See Also:
    • replaceNaNs

      public static void replaceNaNs(Mat mat, double newValue)
      Replace NaNs in a floating point array.
      Parameters:
      mat - array
      newValue - replacement value
    • fill

      public static void fill(Mat mat, Mat mask, double value)
      Fill the pixels of an image with a specific value, corresponding to a mask.
      Parameters:
      mat - input image
      mask - binary mask
      value - replacement value
      See Also:
    • fill

      public static void fill(Mat mat, double value)
      Fill the pixels of an image with a specific value.
      Parameters:
      mat - input image
      value - fill value
      See Also:
    • splitChannels

      public static List<Mat> splitChannels(Mat mat)
      Split channels from a Mat. May be more convenient than OpenCV's built-in approach.
      Parameters:
      mat -
      Returns:
      a list of Mat, containing each split channel in order
    • mergeChannels

      public static Mat mergeChannels(Collection<? extends Mat> channels, Mat dest) throws IllegalArgumentException
      Merge channels from a multichannel Mat. May be more convenient than OpenCV's built-in approach.
      Parameters:
      channels - separate channels
      dest - optional destination (may be null)
      Returns:
      merged Mat, which will be the same as dest if provided
      Throws:
      IllegalArgumentException - if the number of channels in the output would be greater than opencv_core.CV_CN_MAX
    • isFloat

      public static boolean isFloat(Mat mat)
      Returns true if a Mat is a floating point (rather than int) type.
      Parameters:
      mat -
      Returns:
    • floor

      public static void floor(Mat mat)
      Floor values in a floating point Mat. Non-floating point Mats are unchanged. This resembles Math.floor(double) except that non-finite values are left unchanged.
      Parameters:
      mat -
    • round

      public static void round(Mat mat)
      Round values in a floating point Mat. Non-floating point Mats are unchanged. This resembles Math.round(double) except that non-finite values are left unchanged.
      Parameters:
      mat -
    • ceil

      public static void ceil(Mat mat)
      Ceil values in a floating point Mat. Non-floating point Mats are unchanged. This resembles Math.ceil(double) except that non-finite values are left unchanged.
      Parameters:
      mat -
    • ensureContinuous

      public static Mat ensureContinuous(Mat mat, boolean inPlace)
      Ensure a Mat is continuous, creating a copy of the data if necessary.

      This can be necessary before calls to AbstractArray.createBuffer() or AbstractArray.createIndexer() for simpler interpretation of the results.

      Parameters:
      mat - input Mat, which may or may not be continuous
      inPlace - if true, set mat to contain the cloned data if required
      Returns:
      the original mat unchanged if it is already continuous, or cloned data that is continuous if required
      See Also:
    • vConcat

      public static Mat vConcat(Collection<? extends Mat> mats, Mat dest)
      Vertical concatenation for a Mat. May be more convenient than OpenCV's built-in approach.
      Parameters:
      mats - mats to concatenate
      dest - optional destination (may be null)
      Returns:
      merged Mat, which will be the same as dest if provided
    • hConcat

      public static Mat hConcat(Collection<? extends Mat> mats, Mat dest)
      Horizontal concatenation for a Mat. May be more convenient than OpenCV's built-in approach.
      Parameters:
      mats - mats to concatenate
      dest - optional destination (may be null)
      Returns:
      merged Mat, which will be the same as dest if provided
    • applyToChannels

      public static void applyToChannels(Mat input, Consumer<Mat> fun)
      Apply a method that modifies a Mat in-place to all channels of the Mat, merging the result and storing the result in-place.
      Parameters:
      input - the (possibly-multichannel) mat
      fun - the consumer to apply
    • matToBufferedImage

      public static BufferedImage matToBufferedImage(Mat mat)
      Convert a Mat to a BufferedImage.

      This is equivalent to matToBufferedImage(mat, null); As such, the ColorModel may or may not end up being something useful.

      Parameters:
      mat -
      Returns:
      See Also:
    • matToBufferedImage

      public static BufferedImage matToBufferedImage(Mat mat, ColorModel colorModel)
      Convert a Mat to a BufferedImage.

      If no ColorModel is specified, a grayscale model will be used for single-channel 8-bit images and RGB/ARGB for 3/4 channel 8-bit images.

      For all other cases a ColorModel should be specified for meaningful display.

      Parameters:
      mat -
      colorModel -
      Returns:
    • imageToMatRGB

      public static Mat imageToMatRGB(BufferedImage img, boolean includeAlpha)
      Extract 8-bit unsigned pixels from a BufferedImage as a multichannel RGB(A) Mat.
      Parameters:
      img - input image
      includeAlpha - if true, return any available alpha data as a 4th channel.
      Returns:
    • imageToMatBGR

      public static Mat imageToMatBGR(BufferedImage img, boolean includeAlpha)
      Extract 8-bit unsigned pixels from a BufferedImage as a multichannel BGR(A) Mat.
      Parameters:
      img - input image
      includeAlpha - if true, return any available alpha data as a 4th channel.
      Returns:
    • labelImage

      @Deprecated public static void labelImage(Mat matBinary, Mat matLabels, int contourRetrievalMode)
      Deprecated.
      Create a labelled image from a binary image using findContours and drawContours.
      Parameters:
      matBinary -
      matLabels -
      contourRetrievalMode - defined within OpenCV findContours
    • addNoise

      public static void addNoise(Mat mat, double mean, double stdDev)
      Add Gaussian noise with specified mean and standard deviation to all channels of a Mat. This is similar to opencv_core.randn(Mat, Mat, Mat), but supports any number of channels.
      Parameters:
      mat - image to which noise should be added
      mean - noise mean
      stdDev - noise standard deviation
    • median

      public static double median(Mat mat)
      Get the median pixel value in a Mat, ignoring NaNs. This does not distinguish between channels.
      Parameters:
      mat -
      Returns:
    • percentiles

      public static double[] percentiles(Mat mat, double... percentiles)
      Get percentile values for all pixels in a Mat, ignoring NaNs.

      Note that the behavior of this method was changed for v0.4.0 to match NumPy's 'linear' method to calculate percentiles (which is NumPy's current default at the time of writing).

      Parameters:
      mat -
      percentiles - requested percentiles (must be between 0 and 100)
      Returns:
      percentile values, in the same order as the input percentiles
    • mean

      public static double mean(Mat mat)
      Get the mean of an image, across all pixels (regardless of channels), ignoring NaNs.
      Parameters:
      mat -
      Returns:
      the mean of all pixels in the image
    • channelMean

      public static double[] channelMean(Mat mat)
      Get the mean of an image channel, ignoring NaNs.
      Parameters:
      mat -
      Returns:
      an array of channel means; the length equals mat.channels()
    • stdDev

      public static double stdDev(Mat mat)
      Get the standard deviation of an image, across all pixels (regardless of channels), ignoring NaNs.
      Parameters:
      mat -
      Returns:
      the standard deviation of all pixels in the image
    • channelStdDev

      public static double[] channelStdDev(Mat mat)
      Get the standard deviation of image channels, ignoring NaNs.
      Parameters:
      mat -
      Returns:
      an array of channel standard deviation; the length equals mat.channels()
    • sum

      public static double sum(Mat mat)
      Get the sum of an image, across all pixels (regardless of channels), ignoring NaNs.
      Parameters:
      mat -
      Returns:
      the sum of all pixels in the image
    • channelSum

      public static double[] channelSum(Mat mat)
      Get the sum of image channels, ignoring NaNs.
      Parameters:
      mat -
      Returns:
      an array of channel sums; the length equals mat.channels()
    • minimum

      public static double minimum(Mat mat)
      Get the minimum value in an image, across all pixels (regardless of channels), ignoring NaNs.
      Parameters:
      mat -
      Returns:
      the minimum of all pixels in the image
    • channelMinimum

      public static double[] channelMinimum(Mat mat)
      Get the minimum of an image channel, ignoring NaNs.
      Parameters:
      mat -
      Returns:
      an array of channel minima; the length equals mat.channels()
    • maximum

      public static double maximum(Mat mat)
      Get the maximum value in an image, across all pixels (regardless of channels), ignoring NaNs.
      Parameters:
      mat -
      Returns:
      the maximum of all pixels in the image
    • channelMaximum

      public static double[] channelMaximum(Mat mat)
      Get the minimum of an image channel, ignoring NaNs.
      Parameters:
      mat -
      Returns:
      an array of channel minima; the length equals mat.channels()
    • typeToChannels

      public static int typeToChannels(int type)
      Determine the number of channels from a specified Mat type (which also encodes depth).
      Parameters:
      type -
      Returns:
      See Also:
    • typeToDepth

      public static int typeToDepth(int type)
      Determine the depth from a specified Mat type (which may also encode the number of channels).
      Parameters:
      type -
      Returns:
      See Also:
    • scalarMatWithType

      public static Mat scalarMatWithType(double value, int type)
      Create a 1x1 Mat with a specific value, with 1 or more channels. If necessary, clipping or rounding is applied.
      Parameters:
      value - the value to include in the Mat
      type - type of the image; this may contain additional channels if required.
      Returns:
      a Mat with one pixel containing the closest value supported by the type
    • scalarMat

      public static Mat scalarMat(double value, int depth)
      Create a 1x1 single-channel Mat with a specific value. If necessary, clipping or rounding is applied.
      Parameters:
      value - the value to include in the Mat
      depth - depth of the image; if a type (including channels) is supplied instead, the channel information is removed.
      Returns:
      a Mat with one pixel containing the closest value supported by the type
    • putPixelsUnsigned

      public static void putPixelsUnsigned(Mat mat, byte[] pixels)
      Set pixels from a byte array.

      There is no real error checking; it is assumed that the pixel array is in the appropriate format.

      Parameters:
      mat -
      pixels -
    • putPixelsFloat

      public static void putPixelsFloat(Mat mat, float[] pixels)
      Set pixels from a float array.

      There is no real error checking; it is assumed that the pixel array is in the appropriate format.

      Parameters:
      mat -
      pixels -
    • getCircularStructuringElement

      @Deprecated public static Mat getCircularStructuringElement(int radius)
      Deprecated.
      createDisk(int, boolean) gives more reliable shapes.
      Create a Mat depicting a circle of the specified radius.

      Pixels within the circle have the value 1, pixels outside are 0.

      Parameters:
      radius -
      Returns:
    • createDisk

      public static Mat createDisk(int radius, boolean doMean)
      Create a disk filter. This is a rasterized approximation of a filled circle with the specified radius.
      Parameters:
      radius - radius of the disk; must be > 0
      doMean - if true, normalize kernel by dividing by the sum of all elements. If false, all 'inside' elements are 1 and all 'outside' elements are 0.
      Returns:
      a Mat of size radius*2+1 that depicts a filled circle
    • invertBinary

      public static void invertBinary(Mat matBinary, Mat matDest)
      Invert a binary image.

      Specifically, sets all zero pixels to 255 and all non-zero pixels to 0.

      Parameters:
      matBinary -
      matDest -
    • extractPixels

      public static float[] extractPixels(Mat mat, float[] pixels)
      Extract pixels as a float[] array.

      In QuPath v0.2 this would return only the pixels in the first channel. In v0.3+ it should return all pixels.

      Parameters:
      mat -
      pixels -
      Returns:
    • extractPixels

      public static double[] extractPixels(Mat mat, double[] pixels)
      Extract pixels as a double array.
      Parameters:
      mat -
      pixels -
      Returns:
    • extractDoubles

      public static double[] extractDoubles(Mat mat)
      Extract pixels as a double array.
      Parameters:
      mat -
      Returns:
    • extractFloats

      public static float[] extractFloats(Mat mat)
      Extract pixels as a float array.
      Parameters:
      mat -
      Returns:
    • matToSimpleImage

      public static SimpleImage matToSimpleImage(Mat mat, int channel)
      Convert a Mat to a SimpleImage.
      Parameters:
      mat -
      channel -
      Returns:
    • fillSmallHoles

      public static void fillSmallHoles(Mat matBinary, double maxArea)
      Fill holes in a binary image (1-channel, 8-bit unsigned) with an area <= maxArea.
      Parameters:
      matBinary -
      maxArea -
    • watershedIntensitySplit

      public static void watershedIntensitySplit(Mat matBinary, Mat matWatershedIntensities, double threshold, int maximaRadius)
      Apply a watershed transform to refine a binary image, guided either by a distance transform or a supplied intensity image.
      Parameters:
      matBinary - thresholded, 8-bit unsigned integer binary image
      matWatershedIntensities - optional intensity image for applying watershed transform; if not set, distance transform of binary will be used
      threshold -
      maximaRadius -
    • matToImageProcessor

      public static ImageProcessor matToImageProcessor(Mat mat)
      Convert a single-channel OpenCV Mat into an ImageJ ImageProcessor.
      Parameters:
      mat -
      Returns:
    • matToImagePlus

      public static ImagePlus matToImagePlus(Mat mat, String title)
      Convert an OpenCV Mat into an ImageJ ImagePlus.
      Parameters:
      mat -
      title -
      Returns:
    • matToImagePlus

      public static ImagePlus matToImagePlus(String title, Mat... mats)
      Convert an OpenCV MatVector into an ImageJ ImagePlus.
      Parameters:
      title -
      mats -
      Returns:
    • getGaussianDeriv

      public static double[] getGaussianDeriv(double sigma, int order, int length)
      Get filter coefficients for a 1D Gaussian (derivative) kernel.
      Parameters:
      sigma - Gaussian sigma
      order - order of the derivative: 0, ('standard' Gaussian filter), 1 (first derivative) or 2 (second derivative)
      length - number of coefficients in the kernel; in general, this should be an odd number
      Returns:
    • getGaussianDerivKernel

      public static Mat getGaussianDerivKernel(double sigma, int order, boolean doColumn)
      Get filter coefficients for a 1D Gaussian (derivative) kernel.
      Parameters:
      sigma - Gaussian sigma
      order - order of the derivative: 0, ('standard' Gaussian filter), 1 (first derivative) or 2 (second derivative)
      doColumn - if true, return coefficients as a column vector rather than a row vector (default)
      Returns:
    • filterSingleZ

      public static Mat filterSingleZ(List<Mat> mats, double[] kernel, int ind3D, int border)
      Apply a filter along the 'list' dimension for a list of Mats, computing the value for a single entry. This is effectively computing a weighted sum of images in the list.

      Note: this method does not change the depth of the input images. If a floating point output is needed, the Mats should be converted before input.

      Parameters:
      mats -
      kernel -
      ind3D -
      border -
      Returns:
    • filterZ

      public static List<Mat> filterZ(List<Mat> mats, Mat kernelZ, int ind3D, int border)
      Filter filter along entries in the input list.

      If each Mat in the list can be considered a consecutive 2D image plane from a z-stack, this can be considered filtering along the z-dimension.

      Parameters:
      mats -
      kernelZ -
      ind3D - if -1, return filtered results for all mats, otherwise only return results for the mat at the specified ind3D
      border -
      Returns:
    • extractZStack

      public static List<Mat> extractZStack(ImageServer<BufferedImage> server, RegionRequest request, int zMin, int zMax) throws IOException
      Extract a list of Mats, where each Mat corresponds to a z-slice.
      Parameters:
      server -
      request -
      zMin - first z slice, inclusive
      zMax - last z slice, exclusive
      Returns:
      Throws:
      IOException
    • extractZStack

      public static List<Mat> extractZStack(ImageServer<BufferedImage> server, RegionRequest request) throws IOException
      Extract a list of Mats, where each Mat corresponds to a z-slice, for all available z-slices of a region.
      Parameters:
      server -
      request -
      Returns:
      Throws:
      IOException
      See Also:
    • crop

      public static Mat crop(Mat mat, int x, int y, int width, int height)
      Crop a region from a Mat based on its bounding box, returning a new image (not a subregion).
      Parameters:
      mat -
      x -
      y -
      width -
      height -
      Returns:
    • crop

      public static Mat crop(Mat mat, Padding padding)
      Crop a region from a Mat by stripping off padding, returning a new image (not a subregion).
      Parameters:
      mat -
      padding -
      Returns:
      Since:
      v0.4.0
    • applyTiled

      public static Mat applyTiled(Function<Mat,Mat> fun, Mat mat, int tileWidth, int tileHeight, Padding padding, int borderType)
      Apply a function to a Mat that strictly requires a specific input size. The output is expected to have the same size as the input, but may have a different number of channels.

      This method can be used to:

      • Split larger input into tiles of the required size, apply the function and merge the result
      • Pad smaller input into tiles of the required size, apply the function and strip padding from the result
      If the image dimensions are not an exact multiple of the requested tile sizes, both steps may be required.

      Important! If the output (width & height) of the function is smaller than the input, it will resized to have the same dimensions and a warning will be logged.

      Parameters:
      fun - the function to apply to the input
      mat - the input Mat
      tileWidth - the strict tile width required by the input
      tileHeight - the strict tile height required by the input
      padding - padding to apply for internal tiling. Note that if the entire image needs to be padded, this should be done before input.
      borderType - an OpenCV border type, in case padding is needed
      Returns:
      the result of applying fun to mat, having applied any necessary tiling along the way
    • sepFilter2D

      public static void sepFilter2D(Mat mat, Mat kx, Mat ky)
      Apply a separable filter to an image, with symmetric boundary padding.
      Parameters:
      mat - input image
      kx - horizontal kernel
      ky - vertical kernel
    • sepFilter2D

      public static void sepFilter2D(Mat mat, Mat kx, Mat ky, int borderType)
      Apply a separable filter to an image.
      Parameters:
      mat - input image
      kx - horizontal kernel
      ky - vertical kernel
      borderType - OpenCV border type for boundary padding
    • filter2D

      public static void filter2D(Mat mat, Mat kernel)
      Apply a 2D filter to all channels of an image, with symmetric boundary padding.
      Parameters:
      mat - input image
      kernel - filter kernel
    • filter2D

      public static void filter2D(Mat mat, Mat kernel, int borderType)
      Apply a 2D filter to all channels of an image.
      Parameters:
      mat - input image
      kernel - filter kernel
      borderType - OpenCV border type for boundary padding
    • meanFilter

      public static void meanFilter(Mat mat, int radius, int borderType)
      Apply a circular 2D mean filter to all channels of an image.
      Parameters:
      mat - input image
      radius - filter radius
      borderType - OpenCV border type for boundary padding
      See Also:
    • meanFilter

      public static void meanFilter(Mat mat, int radius)
      Apply a circular 2D mean filter to all channels of an image, with symmetric boundary padding.
      Parameters:
      mat - input image
      radius - filter radius
      See Also:
    • sumFilter

      public static void sumFilter(Mat mat, int radius, int borderType)
      Apply a circular 2D sum filter to all channels of an image.
      Parameters:
      mat - input image
      radius - filter radius
      borderType - OpenCV border type for boundary padding
      See Also:
    • sumFilter

      public static void sumFilter(Mat mat, int radius)
      Apply a circular 2D sum filter to all channels of an image, with symmetric boundary padding.
      Parameters:
      mat - input image
      radius - filter radius
      See Also:
    • varianceFilter

      public static void varianceFilter(Mat mat, int radius, int borderType)
      Apply a circular 2D local variance filter to all channels of an image.
      Parameters:
      mat - input image
      radius - filter radius
      borderType - OpenCV border type for boundary padding
      See Also:
    • varianceFilter

      public static void varianceFilter(Mat mat, int radius)
      Apply a circular 2D local variance filter to all channels of an image, with symmetric boundary padding.
      Parameters:
      mat - input image
      radius - filter radius
      See Also:
    • stdDevFilter

      public static void stdDevFilter(Mat mat, int radius, int borderType)
      Apply a circular 2D local standard deviation filter to all channels of an image.
      Parameters:
      mat - input image
      radius - filter radius
      borderType - OpenCV border type for boundary padding
      See Also:
    • stdDevFilter

      public static void stdDevFilter(Mat mat, int radius)
      Apply a circular 2D local standard deviation filter to all channels of an image, with symmetric boundary padding.
      Parameters:
      mat - input image
      radius - filter radius
      See Also:
    • maximumFilter

      public static void maximumFilter(Mat mat, int radius)
      Apply a 2D maximum filter (dilation) to all channels of an image.
      Parameters:
      mat - input image
      radius - radius of the disk structuring element
    • minimumFilter

      public static void minimumFilter(Mat mat, int radius)
      Apply a 2D minimum filter (erosion) to all channels of an image.
      Parameters:
      mat - input image
      radius - radius of the disk structuring element
    • closingFilter

      public static void closingFilter(Mat mat, int radius)
      Apply a 2D closing filter (dilation followed by erosion) to all channels of an image.
      Parameters:
      mat - input image
      radius - radius of the disk structuring element
    • openingFilter

      public static void openingFilter(Mat mat, int radius)
      Apply a 2D opening filter (erosion followed by dilation) to all channels of an image.
      Parameters:
      mat - input image
      radius - radius of the disk structuring element
    • gaussianFilter

      public static void gaussianFilter(Mat mat, double sigma, int borderType)
      Apply a 2D Gaussian filter to all channels of an image.
      Parameters:
      mat - input image
      sigma - filter sigma value
      borderType - OpenCV border type for boundary padding
    • gaussianFilter

      public static void gaussianFilter(Mat mat, double sigma)
      Apply a 2D Gaussian filter to all channels of an image, with symmetric boundary padding.
      Parameters:
      mat - input image
      sigma - filter sigma value
    • label

      public static Mat label(Mat matBinary, int connectivity)
      Label connected components for non-zero pixels in an image.
      Parameters:
      matBinary - binary image to label
      connectivity - either 4 or 8
      Returns:
      an integer labelled image (CV_32S)
    • label

      public static int label(Mat matBinary, Mat matLabels, int connectivity)
      Label connected components for non-zero pixels in an image.
      Parameters:
      matBinary - binary image to label
      matLabels - labelled image to store the output
      connectivity - either 4 or 8
      Returns:
      number of connected components, equal to the value of the highest integer label
    • createROIs

      public static Map<Number,ROI> createROIs(Mat matLabels, RegionRequest region, int minLabel, int maxLabel)
      Convert integer labels into ROIs.
      Parameters:
      matLabels - labelled image; each label should be an integer value
      region - region used to convert coordinates into the full image space (optional)
      minLabel - minimum label; usually 1, but may be 0 if a background ROI should be created
      maxLabel - maximum label; if less than minLabel, the maximum label will be found in the image and used
      Returns:
      an ordered map containing all the ROIs that could be found; corresponding labels are keys in the map // * @see #findROIs(Mat, RegionRequest, int, int)
      See Also:
    • createDetections

      public static List<PathObject> createDetections(Mat matLabels, RegionRequest region, int minLabel, int maxLabel)
      Create detection objects by tracing contours in a labelled image.
      Parameters:
      matLabels - labelled image
      region - region used to convert coordinates into the full image space (optional)
      minLabel - minimum label; usually 1, but may be 0 if a background ROI should be created
      maxLabel - maximum label; if less than minLabel, the maximum label will be found in the image and used
      Returns:
      detection objects generated by tracing contours
      See Also:
    • createAnnotations

      public static List<PathObject> createAnnotations(Mat matLabels, RegionRequest region, int minLabel, int maxLabel)
      Create annotation objects by tracing contours in a labelled image.
      Parameters:
      matLabels - labelled image
      region - region used to convert coordinates into the full image space (optional)
      minLabel - minimum label; usually 1, but may be 0 if a background ROI should be created
      maxLabel - maximum label; if less than minLabel, the maximum label will be found in the image and used
      Returns:
      annotation objects generated by tracing contours
      See Also:
    • createObjects

      public static List<PathObject> createObjects(Mat matLabels, RegionRequest region, int minLabel, int maxLabel, BiFunction<ROI,Number,PathObject> creator)
      Create objects by tracing contours in a labelled image.
      Parameters:
      matLabels - labelled image
      region - region used to convert coordinates into the full image space (optional)
      minLabel - minimum label; usually 1, but may be 0 if a background ROI should be created
      maxLabel - maximum label; if less than minLabel, the maximum label will be found in the image and used
      creator - function used to generate objects from ROIs
      Returns:
      objects generated by tracing contours
      See Also:
    • createCells

      public static List<PathObject> createCells(Mat matLabelsNuclei, Mat matLabelsCells, RegionRequest region, int minLabel, int maxLabel)
      Create cell objects by tracing contours in a labelled image.
      Parameters:
      matLabelsNuclei - labelled image for the cell nuclei
      matLabelsCells - labelled image for the full cell; labels must correspond to those in matLabelsNuclei
      region - region used to convert coordinates into the full image space (optional)
      minLabel - minimum label; usually 1, but may be 0 if a background ROI should be created
      maxLabel - maximum label; if less than minLabel, the maximum label will be found in the image and used
      Returns:
      cell objects generated by tracing contours
      See Also:
    • findRegionalMaxima

      public static Mat findRegionalMaxima(Mat mat)
      Get the regional maxima within a Mat, providing the output as a labeled image.
      Parameters:
      mat - image containing maxima; must be 2D and single-channel
      Returns:
    • physicalMemory

      public static String physicalMemory()
      Get a brief, one-line report on current physical memory use, based on JavaCPP's Pointer class. This is suitable for logging if required.
      Returns:
      See Also:
    • trackedMemory

      public static String trackedMemory()
      Get a brief, one-line report on tracked memory use, based on JavaCPP's Pointer class. This is suitable for logging if required.
      Returns:
      See Also:
    • memoryReport

      public static String memoryReport(CharSequence delimiter)
      Create a brief report on memory use, based on JavaCPP's Pointer class.
      Parameters:
      delimiter - delimiter to use between elements of the report, e.g. ", " or "\n"
      Returns:
      See Also:
    • findMaxima

      public static Collection<OpenCVTools.IndexedPixel> findMaxima(Mat mat, Mat mask)
      Find maxima within an image.
      Parameters:
      mat - image containing maxima; must be 2D and single-channel
      mask - optional mask
      Returns:
    • getMaskedPixels

      public static List<OpenCVTools.IndexedPixel> getMaskedPixels(Mat mat, Mat mask)
      Extract all the masked pixels within an image.
      Parameters:
      mat - input image; must be single-channel
      mask - mask of the same size as mat
      Returns:
      list of pixels, including their indices and values
    • extractMaskedFloats

      public static float[] extractMaskedFloats(Mat input, Mat mask, int channel)

      Extract pixels from an image using a mask, limited to the specified channel index.

      The mask can have one or multiple channels:

      • If the mask has only one channel, this channel is used.
      • If the mask is multichannel, only the specified channel is used.

      The input and the mask must have the same dimensions.

      Parameters:
      input - the image from where the pixels should be extracted
      mask - the mask to apply to the input
      channel - the channel index (zero-based) to consider
      Returns:
      a float array containing the values of the input filtered by the mask
      Throws:
      IllegalArgumentException - when the input and the mask don't have the same dimensions
    • extractMaskedDoubles

      public static double[] extractMaskedDoubles(Mat input, Mat mask, int channel)

      Extract pixels from an image using a mask, limited to the specified channel index.

      The mask can have one or multiple channels:

      • If the mask has only one channel, this channel is used.
      • If the mask is multichannel, only the specified channel is used.

      The input and the mask must have the same dimensions.

      Parameters:
      input - the image from where the pixels should be extracted
      mask - the mask to apply to the input
      channel - the channel index (zero-based) to consider
      Returns:
      a double array containing the values of the input filtered by the mask
      Throws:
      IllegalArgumentException - when the input and the mask don't have the same dimensions
    • shrinkLabels

      public static Mat shrinkLabels(Mat mat)
      Shrink labels to a single point. This works by effectively iterating through each label, and retaining only the labeled pixel that is closest to the centroid of all pixels with the same label - setting all other pixels within the component to zero.
      Parameters:
      mat - label mat (must be CV_32S)
      Returns:
      the labeled image, with only one pixel per label greater than zero