Magick++ STL Support

Magick++ provides a set of Standard Template Libary (STL ) algorithms for operating across ranges of image frames in a container. It also provides a set of STL unary function objects to apply an operation on image frames in a container via an algorithm which uses unary function objects. A good example of a standard algorithm which is useful for processing containers of image frames is the STL for_each algorithm which invokes a unary function object on a range of container elements.

Magick++ uses a limited set of template argument types. The current template argument types are:

Container
A container having the properties of a Back Insertion Sequence . Sequences support forward iterators and Back Insertion Sequences support the additional abilty to append an element via push_back(). Common compatable container types are the STL < vector > and <list > template containers. This template argument is usually used to represent an output container in which one or more image frames may be appended. Containers like STL <vector > which have a given default capacity may need to have their capacity adjusted via reserve() to a larger capacity in order to support the expected final size . Since Magick++ images are very small, it is likely that the default capacity of STL < vector > is sufficient for most situations.
InputIterator
An input iterator used to express a position in a container. These template arguments are typically used to represent a range of elements with first_ representing the first element to be processed and last_ representing the element to stop at. When processing the entire contents of a container, it is handy to know that STL containers usually provide the begin() and end() methods to return input interators which correspond with the first and last elements, respectively.
The following is an example of how frames from a GIF animation "test_image_anim.gif" may be appended horizontally with the resulting image written to the file "appended_image.miff":

#include <list>
#include <Magick++.h>
using namespace std;
using namespace Magick;

int main(int /*argc*/,char **/*argv*/)
{
   list<Image> imageList;
   readImages( &imageList, "test_image_anim.gif" );

   Image appended;
   appendImages( &appended, imageList.begin(), imageList.end() );
   appended.write( "appended_image.miff" );
   return 0;
}

The available Magick++ specific STL algorithms for operating on sequences of image frames are shown in the following table:
 
Magick++ STL Algorithms For Image Sequences
Algorithm
Signature
Description
animateImages
InputIterator first_, InputIterator last_ Animate a sequence of image frames. Image frames are displayed in succession, creating an animated effect. The animation options are taken from the first image frame. This feature is only supported under X11 at the moment.
appendImages
Image *appendedImage_, InputIterator first_, InputIterator last_, bool stack_ = false Append a sequence of image frames, writing the result to appendedImage_. All the input image frames must have the same width or height. Image frames of the same width are stacked top-to-bottom. Image frames of the same height are stacked left-to-right. If the stack_ parameter is false, rectangular image frames are stacked left-to-right otherwise top-to-bottom.
averageImages
Image *averagedImage_, InputIterator first_, InputIterator last_ Average a sequence of image frames, writing the result to averagedImage_. All the input image frames must be the same size in pixels.
coalesceImages
Container *coalescedImages_, InputIterator first_, InputIterator last_
Create a coalesced image sequence obtained by "playing" the image sequence (observing page offsets and disposal methods) to create a new image sequence in which all frames are full size and completely rendered. Note that if the original image sequence relied on page offsets and disposal methods that the resulting sequence will be larger (perhaps much larger) then the original. This is useful for GIF animation sequences that have page offsets and disposal methods. The resuting image sequence is returned via coalescedImages_.
deconstructImages
Container *deconstructedImages_, InputIterator first_, InputIterator last_ Break down an image sequence into constituent parts.  This is useful for creating GIF or MNG animation sequences. The input sequence is specified by first_ and last_, and the deconstruted images are returned via deconstructedImages_.
displayImages
InputIterator first_, InputIterator last_ Display a sequence of image frames. Through use of a pop-up menu, image frames may be selected in succession. This feature is fully supported under X11 but may have only limited support in other environments.
Caution: if an image format is is not compatable with the display visual (e.g. JPEG on a colormapped display) then the original image will be altered. Use a copy of the original if this is a problem.
flattenImages
Image *flattendImage_, InputIterator first_, InputIterator last_ Merge a sequence of image frames which represent image layers into a single composited representation. The flattendImage_ parameter points to an existing Image to update with the flattened image. This function is useful for combining Photoshop layers into a single image.
mapImages
InputIterator first_, InputIterator last_, const Image & mapImage_, bool dither_,  bool measureError_ = false Replace the colors of a sequence of images with the closest color from a reference image. Set dither_ to true to enable dithering.  Set measureError_ to true in order to evaluate quantization error.
montageImages
Container *montageImages_, InputIterator first_, InputIterator last_, const Montage &montageOpts_ Create a composite image by combining several separate image frames. Multiple frames may be generated in the output container montageImages_ depending on the tile setting and the number of image frames montaged. Montage options are provided via the parameter montageOpts_ . Options set in the first image frame ( backgroundColor, borderColor , matteColor , fillColor, strokeColor, font, and fontPointsize ) are also used as options by montageImages().
morphImages
Container *morphedImages_, InputIterator first_, InputIterator last_, unsigned int frames_ Morph a seqence of image frames. This algorithm  expands the number of image frames (output to the container morphedImages_) by adding the number of intervening frames specified by frames_ such that the original frames morph (blend) into each other when played as an animation.
mosaicImages
Image *mosaicImage_, InputIterator first_, InputIterator last_ Inlay a number of images to form a single coherent picture. The mosicImage_ argument is updated with a mosaic constructed from the image sequence represented by first_ through last_ .
readImages
Container *sequence_, const std::string &imageSpec_ Read a sequence of image frames into existing container (appending to container sequence_) with image names specified in the string imageSpec_.
Container *sequence_, const Blob &blob_ Read a sequence of image frames into existing container (appending to container sequence_) from Blob blob_.
writeImages
InputIterator first_, InputIterator last_, const std::string &imageSpec_, bool adjoin_ = true Write images in container to file specified by string imageSpec_. Set adjoin_ to false to write a set of image frames via a wildcard imageSpec_ (e.g. image%02d.miff).
The wildcard must be one of %0Nd, %0No, or %0Nx.
Caution: if an image format is selected which is capable of supporting fewer colors than the original image or quantization has been requested, the original image will be quantized to fewer colors. Use a copy of the original if this is a problem.
InputIterator first_, InputIterator last_, Blob *blob_, bool adjoin_ = true Write images in container to in-memory BLOB specified by Blob blob_. Set adjoin_ to false to write a set of image frames via a wildcard imageSpec_ (e.g. image%02d.miff).
Caution: if an image format is selected which is capable of supporting fewer colors than the original image or quantization has been requested, the original image will be quantized to fewer colors. Use a copy of the original if this is a problem.
quantizeImages InputIterator first_, InputIterator last_, bool measureError_ = false Quantize colors in images using current quantization settings. Set measureError_ to true in order to measure quantization error.

 

Magick++ Unary Function Objects

Magick++ unary function objects inherit from the STL unary_function template class . The STL unary_function template class is of the form
unary_function<Arg, Result>
and expects that derived classes implement a method of the form:
Result operator()( Arg argument_ );
which is invoked by algorithms using the function object. In the case of unary function objects defined by Magick++, the invoked function looks like:
void operator()( Image &image_);
with a typical implementation looking similar to:
void operator()( Image &image_ )
  {
    image_.contrast( _sharpen );
  }
where contrast is an Image method and _sharpen is an argument stored within the function object by its contructor. Since constructors may be polymorphic, a given function object may have several constructors and selects the appropriate Image method based on the arguments supplied.

In essence, unary function objects (as provided by Magick++) simply provide the means to construct an object which caches arguments for later use by an algorithm designed for use with unary function objects. There is a unary function object corresponding each algorithm provided by the Image class and there is a contructor available compatable with each synonymous method in the Image class.

The unary function objects that Magick++ provides to support manipulating images are shown in the following table:
 
Magick++ Unary Function Objects For Image Manipulation
Function Object Constructor Signatures(s) Description
adaptiveThresholdImage
unsigned int width, unsigned int height, unsigned offset = 0
Apply adaptive thresholding to the image. Adaptive thresholding is useful if the ideal threshold level is not known in advance, or if the illumination gradient is not constant across the image. Adaptive thresholding works by evaulating the mean (average) of a pixel region (size specified by width and height) and using the mean as the thresholding value. In order to remove residual noise from the background, the threshold may be adjusted by subtracting a constant offset (default zero) from the mean to compute the threshold.
addNoiseImage
NoiseType noiseType_ Add noise to image with specified noise type.
affineTransformImage
const DrawableAffine &affine_
Transform image by specified affine (or free transform) matrix.
annotateImage
const std::string &text_, const Geometry &location_ Annotate with text using specified text, bounding area, placement gravity, and rotation. If boundingArea_ is invalid, then bounding area is entire image.
std::string text_, const Geometry &boundingArea_, GravityType gravity_ Annotate using specified text, bounding area, and placement gravity. If boundingArea_ is invalid, then bounding area is entire image.
const std::string &text_, const Geometry &boundingArea_, GravityType gravity_, double degrees_,  Annotate with text using specified text, bounding area, placement gravity, and rotation. If boundingArea_ is invalid, then bounding area is entire image.
const std::string &text_, GravityType gravity_ Annotate with text (bounding area is entire image) and placement gravity.
blurImage
const double radius_ = 1, const double sigma_ = 0.5 Blur image. The radius_ parameter specifies the radius of the Gaussian, in pixels, not counting the center pixel.  The sigma_ parameter specifies the standard deviation of the Laplacian, in pixels.
borderImage
const Geometry &geometry_ = "6x6+0+0" Border image (add border to image).  The color of the border is specified by the borderColor attribute.
charcoalImage
const double radius_ = 1, const double sigma_ = 0.5 Charcoal effect image (looks like charcoal sketch). The radius_ parameter specifies the radius of the Gaussian, in pixels, not counting the center pixel.  The sigma_ parameter specifies the standard deviation of the Laplacian, in pixels.
chopImage
const Geometry &geometry_ Chop image (remove vertical or horizontal subregion of image)
colorizeImage
const unsigned int opacityRed_, const unsigned int opacityGreen_, const unsigned int opacityBlue_, const Color &penColor_ Colorize image with pen color, using specified percent opacity for red, green, and blue quantums.
const unsigned int opacity_, const Color &penColor_ Colorize image with pen color, using specified percent opacity.
commentImage
const std::string &comment_ Comment image (add comment string to image).  By default, each image is commented with its file name. Use  this  method to  assign a specific comment to the image.  Optionally you can include the image filename, type, width, height, or other  image  attributes by embedding special format characters.
compositeImage
const Image &compositeImage_, int xOffset_, int yOffset_, CompositeOperator compose_ = InCompositeOp Compose an image onto another at specified offset and using specified algorithm
const Image &compositeImage_, const Geometry &offset_, CompositeOperator compose_ = InCompositeOp
condenseImage
void Condense image (Re-run-length encode image in memory).
contrastImage
unsigned int sharpen_ Contrast image (enhance intensity differences in image)
cropImage
const Geometry &geometry_ Crop image (subregion of original image)
cycleColormap-
Image
int amount_ Cycle image colormap
despeckleImage
void Despeckle image (reduce speckle noise)
drawImage
const Drawable &drawable_ Draw shape or text on image.
const std::list<Drawable > &drawable_ Draw shapes or text on image using a set of Drawable objects contained in an STL list. Use of this method improves drawing performance and allows batching draw objects together in a list for repeated use.
edgeImage
unsigned int radius_ = 0.0 Edge image (hilight edges in image).  The radius is the radius of the pixel neighborhood.. Specify a radius of zero for automatic radius selection.
embossImage
const double radius_ = 1, const double sigma_ = 0.5 Emboss image (hilight edges with 3D effect). The radius_ parameter specifies the radius of the Gaussian, in pixels, not counting the center pixel.  The sigma_ parameter specifies the standard deviation of the Laplacian, in pixels.
enhanceImage
void Enhance image (minimize noise)
equalizeImage
void Equalize image (histogram equalization)
flipImage
void Flip image (reflect each scanline in the vertical direction)
floodFill-
ColorImage
unsigned int x_, unsigned int y_, const Color &fillColor_ Flood-fill color across pixels that match the color of the target pixel and are neighbors of the target pixel. Uses current fuzz setting when determining color match.
const Geometry &point_, const Color &fillColor_
unsigned int x_, unsigned int y_, const Color &fillColor_, const Color &borderColor_ Flood-fill color across pixels starting at target-pixel and stopping at pixels matching specified border color. Uses current fuzz setting when determining color match.
const Geometry &point_, const Color &fillColor_, const Color &borderColor_
floodFill-
TextureImage
unsigned int x_, unsigned int y_,  const Image &texture_ Flood-fill texture across pixels that match the color of the target pixel and are neighbors of the target pixel. Uses current fuzz setting when determining color match.
const Geometry &point_, const Image &texture_
unsigned int x_, unsigned int y_, const Image &texture_, const Color &borderColor_ Flood-fill texture across pixels starting at target-pixel and stopping at pixels matching specified border color. Uses current fuzz setting when determining color match.
const Geometry &point_, const Image &texture_, const Color &borderColor_
flopImage
void  Flop image (reflect each scanline in the horizontal direction)
frameImage
const Geometry &geometry_ = "25x25+6+6" Add decorative frame around image
unsigned int width_, unsigned int height_, int x_, int y_, int innerBevel_ = 0, int outerBevel_ = 0
gammaImage
double gamma_ Gamma correct image (uniform red, green, and blue correction).
double gammaRed_, double gammaGreen_, double gammaBlue_ Gamma correct red, green, and blue channels of image.
gaussianBlurImage
double width_, double sigma_ Gaussian blur image. The number of neighbor pixels to be included in the convolution mask is specified by 'width_'.  For example, a width of one gives a (standard) 3x3 convolution mask. The standard deviation of the gaussian bell curve is specified by 'sigma_'.
implodeImage
double factor_ Implode image (special effect)
labelImage
const string &label_ Assign a label to an image. Use this option to  assign  a  specific label to the image. Optionally you can include the image filename, type, width, height, or scene number in the label by embedding  special format characters. If the first character of string is @, the image label is read from a file titled by the remaining characters in the string. When converting to Postscript, use this  option to specify a header string to print above the image.
levelImage
const double black_point, const double white_point, const double mid_point=1.0
Level image. Adjust the levels of the image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid (gamma), and white points.  The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point (gamma) specifies a gamma correction to apply to the image. White point specifies the lightest color in the image.  Colors brighter than the white point are set to the maximum quantum value. The black and white point have the valid range 0 to MaxRGB while mid (gamma) has a useful range of 0 to ten.
levelChannelImage
const Magick::ChannelType channel, const double black_point, const double white_point, const double mid_point=1.0
Level image channel. Adjust the levels of the image channel by scaling the values falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid (gamma), and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point (gamma) specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value. The black and white point have the valid range 0 to MaxRGB while mid (gamma) has a useful range of 0 to ten.
layerImage
ChannelType layer_ Extract layer from image. Use this option to extract a particular layer from  the image.  MatteLayer,  for  example, is useful for extracting the opacity values from an image.
magnifyImage
void Magnify image by integral size
mapImage
const Image &mapImage_ , bool dither_ = false Remap image colors with closest color from reference image. Set dither_ to true in to apply Floyd/Steinberg error diffusion to the image. By default, color reduction chooses an optimal  set  of colors that best represent the original image. Alternatively, you can  choose  a  particular  set  of colors  from  an image file with this option.
matteFloodfill-
Image
const Color &target_, unsigned int matte_, int x_, int y_, PaintMethod method_ Floodfill designated area with a matte value
medianFilterImage const double radius_ = 0.0 Filter image by replacing each pixel component with the median color in a circular neighborhood
minifyImage
void Reduce image by integral size
modulateImage
double brightness_, double saturation_, double hue_ Modulate percent hue, saturation, and brightness of an image. Modulation of saturation and brightness is as a ratio of the current value (1.0 for no change). Modulation of hue is an absolute rotation of -180 degrees to +180 degrees from the current position corresponding to an argument range of 0 to 2.0 (1.0 for no change).
negateImage
bool grayscale_ = false Negate colors in image.  Replace every pixel with its complementary color (white becomes black, yellow becomes blue, etc.).  Set grayscale to only negate grayscale values in image.
normalizeImage
void Normalize image (increase contrast by normalizing the pixel values to span the full range of color values).
oilPaintImage
unsigned int radius_ = 3 Oilpaint image (image looks like oil painting)
opacityImage
unsigned int opacity_ Set or attenuate the opacity channel in the image. If the image pixels are opaque then they are set to the specified opacity value, otherwise they are blended with the supplied opacity value.  The value of opacity_ ranges from 0 (completely opaque) to MaxRGB. The defines OpaqueOpacity and TransparentOpacity are available to specify completely opaque or completely transparent, respectively.
opaqueImage
const Color &opaqueColor_, const Color &penColor_ Change color of pixels matching opaqueColor_ to specified penColor_.
quantizeImage
bool measureError_ = false Quantize image (reduce number of colors). Set measureError_ to true in order to calculate error attributes.
raiseImage
const Geometry &geometry_ = "6x6+0+0",  bool raisedFlag_ =  false Raise image (lighten or darken the edges of an image to give a 3-D raised or lowered effect)
reduceNoise-
Image
void Reduce noise in image using a noise peak elimination filter.
unsigned int order_
rollImage
int columns_, int rows_ Roll image (rolls image vertically and horizontally) by specified number of columnms and rows)
rotateImage
double degrees_ Rotate image counter-clockwise by specified number of degrees
sampleImage
const Geometry &geometry_  Resize image by using pixel sampling algorithm
scaleImage
const Geometry &geometry_ Resize image by using simple ratio algorithm
segmentImage
double clusterThreshold_ = 1.0,
double smoothingThreshold_ = 1.5
Segment (coalesce similar image components) by analyzing the histograms of the color components and identifying units that are homogeneous with the fuzzy c-means technique. Also uses quantizeColorSpace and verbose image attributes. Specify clusterThreshold_ , as the number  of  pixels  each cluster  must exceed the cluster threshold to be considered valid. SmoothingThreshold_ eliminates noise in the  second derivative of the histogram. As the value is  increased, you can  expect  a  smoother second derivative.  The default is 1.5.
shadeImage
double azimuth_ = 30, double elevation_ = 30,
bool colorShading_ = false
Shade image using distant light source. Specify azimuth_ and elevation_ as the  position  of  the light source. By default, the shading results as a grayscale image.. Set colorShading_ to true to shade the red, green, and blue components of the image.
sharpenImage
const double radius_ = 1, const double sigma_ = 0.5 Sharpen pixels in image. The radius_ parameter specifies the radius of the Gaussian, in pixels, not counting the center pixel.  The sigma_ parameter specifies the standard deviation of the Laplacian, in pixels.
shaveImage
const Geometry &geometry_ Shave pixels from image edges.
shearImage
double xShearAngle_, double yShearAngle_ Shear image (create parallelogram by sliding image by X or Y axis).  Shearing slides one edge of an image along the X  or  Y axis,  creating  a parallelogram.  An X direction shear slides an edge along the X axis, while  a  Y  direction shear  slides  an edge along the Y axis.  The amount of the shear is controlled by a shear angle.  For X direction  shears,  x  degrees is measured relative to the Y axis, and similarly, for Y direction shears  y  degrees is measured relative to the X axis. Empty triangles left over from shearing the  image  are filled  with  the  color  defined as borderColor
solarizeImage
double factor_ Solarize image (similar to effect seen when exposing a photographic film to light during the development process)
spreadImage
unsigned int amount_ = 3 Spread pixels randomly within image by specified amount
steganoImage
const Image &watermark_ Add a digital watermark to the image (based on second image)
stereoImage
const Image &rightImage_ Create an image which appears in stereo when viewed with red-blue glasses (Red image on left, blue on right)
swirlImage
double degrees_ Swirl image (image pixels are rotated by degrees)
textureImage
const Image &texture_ Layer a texture on image background
thresholdImage
double threshold_ Threshold image
transformImage
const Geometry &imageGeometry_ Transform image based on image and crop geometries. Crop geometry is optional.
const Geometry &imageGeometry_, const Geometry &cropGeometry_ 
transparentImage
const Color &color_ Add matte image to image, setting pixels matching color to transparent.
trimImage
void Trim edges that are the background color from the image.
waveImage
double amplitude_ = 25.0, double wavelength_ = 150.0 Alter an image along a sine wave.
zoomImage
const Geometry &geometry_ Zoom image to specified size.

Function objects are available to set attributes on image frames which are equivalent to methods in the Image object. These function objects allow setting an option across a range of image frames using f or_each().

The following code is an example of how the color 'red' may be set to transparent in a GIF animation:

list<image> images;
readImages( &images, "animation.gif" );
for_each ( images.begin(), images.end(), transparentImage( "red" )  );
writeImages( images.begin(), images.end(), "animation.gif" );

The available function objects for setting image attributes are
 
Image Attributes
Attribute
Type
Constructor Signature(s)
Description
adjoinImage
bool bool flag_ Join images into a single multi-image file.
antiAliasImage
bool bool flag_ Control antialiasing of rendered Postscript and Postscript or TrueType fonts. Enabled by default.
animation-
DelayImage
unsigned int (0 to 65535) unsigned int delay_ Time in 1/100ths of a second (0 to 65535) which must expire before displaying the next image in an animated sequence. This option is useful for regulating the animation of a sequence  of GIF images within Netscape.
animation-
IterationsImage
unsigned int unsigned int iterations_ Number of iterations to loop an animation (e.g. Netscape loop extension) for.
background-
ColorImage
Color const Color &color_ Image background color
background-
TextureImage
std::string const string &texture_ Image to use as background texture.
borderColor-
Image
Color  const Color &color_ Image border color
boxColorImage
Color const Color &boxColor_ Base color that annotation text is rendered on.
chroma-
BluePrimaryImage
double x & y double x_, double y_ Chromaticity blue primary point (e.g. x=0.15, y=0.06)
chroma-
GreenPrimaryImage
double x & y double x_, double y_ Chromaticity green primary point (e.g. x=0.3, y=0.6)
chroma-
RedPrimaryImage
double x & y double x_, double y_ Chromaticity red primary point (e.g. x=0.64, y=0.33)
chroma-
WhitePointImage
double x & y double x_, double y_ Chromaticity white point (e.g. x=0.3127, y=0.329)
colorFuzzImage
double double fuzz_ Colors within this distance are considered equal. A number of algorithms search for a target  color. By default the color must be exact. Use this option to match colors that are close to the target color in RGB space.
colorMapImage
Color unsigned int index_, const Color &color_ Color at color-pallet index.
colorSpaceImage ColorspaceType ColorspaceType colorSpace_ The colorspace (e.g. CMYK) used to represent the image pixel colors. Image pixels are always stored as RGB(A) except for the case of CMY(K).
composeImage
CompositeOperator CompositeOperator compose_ Composition operator to be used when composition is implicitly used (such as for image flattening).
compressType-
Image
<