MagickCore, C API: Morphological Erosions, Dilations, Openings, and Closings @ ImageMagick
Author: ImageMagick Studio LLC
Description: ImageMagick® is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats (over 200) including PNG, JPEG, JPEG-2000, GIF, WebP, Postscript, PDF, and SVG. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.
Keywords: magickcore, c, api:, morphological, erosions, dilations, openings, closings, ImageMagick, PerlMagick, image processing, image, photo, software, Magick++, OpenMP, convert

AcquireKernelInfo • CloneKernelInfo • DestroyKernelInfo • MorphologyApply • This is almost identical to the MorphologyPrimative • MorphologyImage • ScaleGeometryKernelInfo • ScaleKernelInfo • ShowKernelInfo • UnityAddKernelInfo • ZeroKernelNans

## AcquireKernelInfo

AcquireKernelInfo() takes the given string (generally supplied by the user) and converts it into a Morphology/Convolution Kernel. This allows users to specify a kernel from a number of pre-defined kernels, or to fully specify their own kernel for a specific Convolution or Morphology Operation.

The kernel so generated can be any rectangular array of floating point values (doubles) with the 'control point' or 'pixel being affected' anywhere within that array of values.

Previously IM was restricted to a square of odd size using the exact center as origin, this is no longer the case, and any rectangular kernel with any value being declared the origin. This in turn allows the use of highly asymmetrical kernels.

The floating point values in the kernel can also include a special value known as 'nan' or 'not a number' to indicate that this value is not part of the kernel array. This allows you to shaped the kernel within its rectangular area. That is 'nan' values provide a 'mask' for the kernel shape. However at least one non-nan value must be provided for correct working of a kernel.

The returned kernel should be freed using the DestroyKernelInfo method when you are finished with it. Do not free this memory yourself.

Input kernel defintion strings can consist of any of three types.

"name:args[[@><]" Select from one of the built in kernels, using the name and geometry arguments supplied. See AcquireKernelBuiltIn()

"WxH[+X+Y][@><]:num, num, num ..." a kernel of size W by H, with W*H floating point numbers following. the 'center' can be optionally be defined at +X+Y (such that +0+0 is top left corner). If not defined the pixel in the center, for odd sizes, or to the immediate top or left of center for even sizes is automatically selected.

"num, num, num, num, ..." list of floating point numbers defining an 'old style' odd sized square kernel. At least 9 values should be provided for a 3x3 square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc. Values can be space or comma separated. This is not recommended.

You can define a 'list of kernels' which can be used by some morphology operators A list is defined as a semi-colon separated list kernels.

" kernel ; kernel ; kernel ; "

Any extra ';' characters, at start, end or between kernel defintions are simply ignored.

The special flags will expand a single kernel, into a list of rotated kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree cyclic rotations, while a '>' will generate a list of 90-degree rotations. The '<' also exands using 90-degree rotates, but giving a 180-degree reflected kernel before the +/- 90-degree rotations, which can be important for Thinning operations.

Note that 'name' kernels will start with an alphabetic character while the new kernel specification has a ':' character in its specification string. If neither is the case, it is assumed an old style of a simple list of numbers generating a odd-sized square kernel has been given.

The format of the AcquireKernal method is:

    KernelInfo *AcquireKernelInfo(const char *kernel_string)

A description of each parameter follows:

kernel_string
  the Morphology/Convolution kernel wanted.

## CloneKernelInfo

CloneKernelInfo() creates a new clone of the given Kernel List so that its can be modified without effecting the original. The cloned kernel should be destroyed using DestoryKernelInfo() when no longer needed.

The format of the CloneKernelInfo method is:

    KernelInfo *CloneKernelInfo(const KernelInfo *kernel)

A description of each parameter follows:

kernel
  the Morphology/Convolution kernel to be cloned

## DestroyKernelInfo

DestroyKernelInfo() frees the memory used by a Convolution/Morphology kernel.

The format of the DestroyKernelInfo method is:

    KernelInfo *DestroyKernelInfo(KernelInfo *kernel)

A description of each parameter follows:

kernel
  the Morphology/Convolution kernel to be destroyed

## MorphologyApply

MorphologyApply() applies a morphological method, multiple times using a list of multiple kernels. This is the method that should be called by other 'operators' that internally use morphology operations as part of their processing.

It is basically equivalent to as MorphologyImage() (see below) but without any user controls. This allows internel programs to use this method to perform a specific task without possible interference by any API user supplied settings.

It is MorphologyImage() task to extract any such user controls, and pass them to this function for processing.

More specifically all given kernels should already be scaled, normalised, and blended appropriatally before being parred to this routine. The appropriate bias, and compose (typically 'UndefinedComposeOp') given.

The format of the MorphologyApply method is:

    Image *MorphologyApply(const Image *image,MorphologyMethod method,
      const ssize_t iterations,const KernelInfo *kernel,
      const CompositeMethod compose,const double bias,
      ExceptionInfo *exception)

A description of each parameter follows:

image
  the source image
method
  the morphology method to be applied.
iterations
  apply the operation this many times (or no change). A value of -1 means loop until no change found. How this is applied may depend on the morphology method. Typically this is a value of 1.
channel
  the channel type.
kernel
  An array of double representing the morphology kernel.
compose
  How to handle or merge multi-kernel results. If 'UndefinedCompositeOp' use default for the Morphology method. If 'NoCompositeOp' force image to be re-iterated by each kernel. Otherwise merge the results using the compose method given.
bias
  Convolution Output Bias.
exception
  return any errors or warnings in this structure.

## This is almost identical to the MorphologyPrimative

This is almost identical to the MorphologyPrimative() function above, but applies the primitive directly to the actual image using two passes, once in each direction, with the results of the previous (and current) row being re-used.

That is after each row is 'Sync'ed' into the image, the next row makes use of those values as part of the calculation of the next row. It repeats, but going in the oppisite (bottom-up) direction.

Because of this 're-use of results' this function can not make use of multi- threaded, parellel processing.

## MorphologyImage

MorphologyImage() applies a user supplied kernel to the image according to the given mophology method.

This function applies any and all user defined settings before calling the above internal function MorphologyApply().

User defined settings include... * Output Bias for Convolution and correlation ("-define convolve:bias=??") * Kernel Scale/normalize settings ("-define convolve:scale=??") This can also includes the addition of a scaled unity kernel. * Show Kernel being applied ("-define morphology:showkernel=1")

Other operators that do not want user supplied options interfering, especially "convolve:bias" and "morphology:showkernel" should use MorphologyApply() directly.

The format of the MorphologyImage method is:

    Image *MorphologyImage(const Image *image,MorphologyMethod method,
      const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception)

A description of each parameter follows:

image
  the image.
method
  the morphology method to be applied.
iterations
  apply the operation this many times (or no change). A value of -1 means loop until no change found. How this is applied may depend on the morphology method. Typically this is a value of 1.
kernel
  An array of double representing the morphology kernel. Warning: kernel may be normalized for the Convolve method.
exception
  return any errors or warnings in this structure.

## ScaleGeometryKernelInfo

ScaleGeometryKernelInfo() takes a geometry argument string, typically provided as a "-set option:convolve:scale {geometry}" user setting, and modifies the kernel according to the parsed arguments of that setting.

The first argument (and any normalization flags) are passed to ScaleKernelInfo() to scale/normalize the kernel. The second argument is then passed to UnityAddKernelInfo() to add a scled unity kernel into the scaled/normalized kernel.

The format of the ScaleGeometryKernelInfo method is:

    void ScaleGeometryKernelInfo(KernelInfo *kernel,
      const double scaling_factor,const MagickStatusType normalize_flags)

A description of each parameter follows:

kernel
  the Morphology/Convolution kernel to modify
  o geometry:

           "-set option:convolve:scale {geometry}" setting.

## ScaleKernelInfo

ScaleKernelInfo() scales the given kernel list by the given amount, with or without normalization of the sum of the kernel values (as per given flags).

By default (no flags given) the values within the kernel is scaled directly using given scaling factor without change.

If either of the two 'normalize_flags' are given the kernel will first be normalized and then further scaled by the scaling factor value given.

Kernel normalization ('normalize_flags' given) is designed to ensure that any use of the kernel scaling factor with 'Convolve' or 'Correlate' morphology methods will fall into -1.0 to +1.0 range. Note that for non-HDRI versions of IM this may cause images to have any negative results clipped, unless some 'bias' is used.

More specifically. Kernels which only contain positive values (such as a 'Gaussian' kernel) will be scaled so that those values sum to +1.0, ensuring a 0.0 to +1.0 output range for non-HDRI images.

For Kernels that contain some negative values, (such as 'Sharpen' kernels) the kernel will be scaled by the absolute of the sum of kernel values, so that it will generally fall within the +/- 1.0 range.

For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel will be scaled by just the sum of the postive values, so that its output range will again fall into the +/- 1.0 range.

For special kernels designed for locating shapes using 'Correlate', (often only containing +1 and -1 values, representing foreground/brackground matching) a special normalization method is provided to scale the positive values separately to those of the negative values, so the kernel will be forced to become a zero-sum kernel better suited to such searches.

WARNING: Correct normalization of the kernel assumes that the '*_range' attributes within the kernel structure have been correctly set during the kernels creation.

NOTE: The values used for 'normalize_flags' have been selected specifically to match the use of geometry options, so that '!' means NormalizeValue, '^' means CorrelateNormalizeValue. All other GeometryFlags values are ignored.

The format of the ScaleKernelInfo method is:

    void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
             const MagickStatusType normalize_flags )

A description of each parameter follows:

kernel
  the Morphology/Convolution kernel
  o scaling_factor:

           zero.  If the kernel is normalized regardless of any flags.

o normalize_flags:

           specifically: NormalizeValue, CorrelateNormalizeValue,
                         and/or PercentValue

## ShowKernelInfo

ShowKernelInfo() outputs the details of the given kernel defination to standard error, generally due to a users 'morphology:showkernel' option request.

The format of the ShowKernel method is:

    void ShowKernelInfo(const KernelInfo *kernel)

A description of each parameter follows:

kernel
  the Morphology/Convolution kernel

## UnityAddKernelInfo

UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel to the given pre-scaled and normalized Kernel. This in effect adds that amount of the original image into the resulting convolution kernel. This value is usually provided by the user as a percentage value in the 'convolve:scale' setting.

The resulting effect is to convert the defined kernels into blended soft-blurs, unsharp kernels or into sharpening kernels.

The format of the UnityAdditionKernelInfo method is:

    void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale )

A description of each parameter follows:

kernel
  the Morphology/Convolution kernel
  o scale:

           the given kernel.

## ZeroKernelNans

ZeroKernelNans() replaces any special 'nan' value that may be present in the kernel with a zero value. This is typically done when the kernel will be used in special hardware (GPU) convolution processors, to simply matters.

The format of the ZeroKernelNans method is:

    void ZeroKernelNans (KernelInfo *kernel)

A description of each parameter follows:

kernel
  the Morphology/Convolution kernel