ImageMagick v6 Examples --
Compositing Images

Index
ImageMagick Examples Preface and Index
Image Composition in IM
Positioning The Overlay Image
Raw Tables of Compose Methods (Separate Page)
Duff-Porter Alpha Composition Methods
Mathematical Compose Methods
Lighting Composition Methods (Light, Dodge, Burn)
Channel Copying Methods
Dissolve one Image Over Another
Blend two images together
Watermark or Modulate Image
Using a Mask to Limit Composed Area
Composite using Image Tiles
Special Composition Methods
MathematicsChange Mask
Image Mapping Composition Methods
Variable Blur,   Displace Mapping

Image Composition is the technique of combining images that have, or do not have, transparency or an alpha channel. This is usually performed using the IM "composite" command. It may also be performed as either part of a larger sequence of operations or internally by other image operators.


Image Composition in IM

Image Composition is the process of merging two (and only two) images in a variety of ways. It is associated with Alpha Composition which describes the result based on which part of the overlay is transparent. Image Composition is used for blending and averaging images, transfering image channels, cutting, joining, or layering odd shaped segments of images. Or, as part of complex mathematical operations.

A good alternate introduction on Image Composition is SVG Compositing in 30 Minutes. Or you can discover precise mathematical details by reading the SVG Alpha Compositing page, which describes the more important image composition methods.

The following commands are the two direct image 'composite' methods available in ImageMagick...

  composite {overlay} {background} [-compose {method}]   {result}

  convert  {background} {overlay} [-compose {method}] -composite   {result}

The "composite" command is the conventional method of compositing in IM. Having a dedicated command demonstrates just how important Image Composition is.

The "convert" operator "-composite" can also do Image Composition as part of a larger image processing task. Note the reversed order of the images when using "convert". The order is practical as you are generally working with a primary canvas over which you prepare and merge images forming a new image. The order of the images is important.

Examples of both techniques (and more) can be reviewed in Layers of Multiple Images; recomended reading before continuing.

Definition and Terms

The more important image is the background image often called the destination image as this image is the one which is modified by Image Composition. The background sets not only the final size of the Image Composition but meta-data, such as 'comments', 'labels', 'density', 'profiles' and so on, are also preserved. It's position is fixed and usually forms the canvas which you are building, thus the name background. Remember this!

The overlay image is often called the source image as it controls how the "-compose" method should modify the fixed background or destination image. The image can be re-positioned relative to the fixed background (usually using "-geometry" and "-gravity" settings). However, both the image and any meta-data it contains, is destroyed when the composite operation is finished.

Sometimes a third mask image is added to the command. This image is used to define and control what parts of the background will be modified and to what degree. See Composite Masking below.

On top of this is a special "-set" option "option:compose:outside-overlay", which if set to 'false' disables any modification to the background image outside the rectangular area that the overlay image covers. See the Copy and Clear compose methods for examples.


The actual composition method is controlled by the "-compose" setting, which defaults to a value of 'Over'. That is, the source image is drawn Over the background image, which is what most people think of when they perform image composition.

Most of this section of IM Examples is used to detail what the various composition 'methods' do and how you can make use of them.

To view the results of the compose methods see Tables of Compose Methods. The tables do not illustrate the method's intended use, just the raw output from various test images.

The compose method is case-insensitive and the '_' or '-' characters are optional. As such the compose method "Dst_Over" can also be specified as: "dst_over", "dst-over", "DstOver", "dstover", or even "dstOVER". They all mean the same thing.

Also, the compose methods: 'Over', 'ATop', 'In' and 'Out' are short for the more verbose compose method names: 'Src_Over', 'Src_ATop', 'Src_In' and 'Src_Out'.

On top of the long list of "-compose" methods there are some that require extra numerical arguments to work correctly.

In the "composite" command these arguments are passed using the special options: "-dissolve", "-blend", "-watermark" ('modulate'), "-displace" and "-distort".

As of IM v6.5.3-4, the "convert" command can pass special arguments to the "-composite" operator by using the special "-set" option "option:compose:args". For examples, see the special Dissolve and Blend methods below.

Image Composition Operators

Apart from the direct two image compositing styles shown above, there are a number of other image operations that also use alpha compositing as part of their internal image processing. These operations are affected by the current "-compose" setting, though they will use either their own internal positioning, or a Layered Image virtual canvas offset positioning technique.

Here is a list of all operators that are known to be affected by the compose setting...

Composite Image Overlays
A link to practical examples using the primary image composition operators. It demonstrates using either the "convert -composite" operator, or the "composite" command, to overly multiple images onto a given canvas, one image at a time.

This uses Geometry/Gravity Settings to determine the position of the overlay image.

Layering Operators
The operators "flatten", "mosaic", and the new "-layers merge" overlay all multiple images in the current image sequence, onto a single new canvas, the size and position of which is determined by the layering operator chosen.

This uses Virtual Canvas/Page Offset Settings to determine the position of the overlay image. (Absolute positions only, the gravity setting is not used)

Edge Expansion Operators
Operators that overlay each individual image on individual canvases. This includes operators such as "-border", "-frame", and "-extent". (See Adding/Removing Image Edges).

No positioning information is used, though "-extent" will make use of gravity.

Draw Images
The "-draw 'image...'" image overlay method will overlay a single external source image over a list of destination images.

It is the only image composition technique available to "mogrify". It gets the 'overlay' image from an external source allowing it to overcome that command's no-list-operator limitation.

Resize and Position information is also given by the user, and these may be gravity effected.

Multi-Sequence Layers Composite
The "-layers composite" operator will let you compose two separate multiple image sequences together, one pair of images at a time, to form a new merged multi-image sequence. It also composes a sequence of images with a single image (which can be either a static 'overlay' image, or a static 'destination' image). It is also the ONLY composition operator to allow you to use BOTH the universal "-gravity" affected "-geometry" offset, or the virtual canvas "-page" offsets of individual images, from that global position.

This composition operator is especially important for composing Image Animations, or other image sequences, as a whole, rather than needing a script to process each pair of images at a time.


Positioning The Overlay Image

Composite Geometry/Gravity Settings

In normal Alpha Composition the "-geometry" setting is used with "-gravity" to position the source image relative to the destination image. Using these settings is covered in great detail in Image Positioning using Gravity.

Note that the size component of "-geometry" is special in that it will Resize an Image (geometry). In "composite" it resizes the source image but for "convert" the last image in the image sequence is resized. This is technically a separate aspect to Image Composition. See Geometry Resize and Layering images with Composite.

In Alpha Composition only two images are involved, the 'source' and the 'destination' (or 'background'), though a third Masking Image may also be provided limiting the affected area of the composition.

Layer Canvas/Page Offsets

The composition of Layered Images use a very different philosophy. All the images (as many as you like) are treated equally in the order given. They all have a "-page" or Page Offset that position each image's top-left corner relative to a virtual canvas 'origin' (the default offset) but without gravity.

To process multiple images a new background image is generated using the current "-background" color with a size that is dependent on the operation being performed. This is assumed to be the 'destination' image (canvas). ALL the images are composited onto this new canvas one at a time in sequence.

Even if only two images are given a new image is still created and two separate compositions are applied. That is, it can be slow. All the images are treated as 'source' images and the order they are listed determines the result.

The 'layer' offset however is NOT gravity affected. As each image can have a separate 'canvas offset' multiple image composition is better applied using Image Layering Operators as well as Multi-Image Sequence Composition for animations.

The two styles are very different positioning techniques and it is important you use the right style for the composition techniques you plan to use.

Both positioning Techniques

Only one composition technqiue, the multi-image sequence Layers Composition operator, allows you to use BOTH positioning methods simultaneously. The layer offsets are used for individual images while composite geometry position (with gravity) is used for global positioning of two separate image sequences.


Duff-Porter Alpha Composition Methods

The Duff-Porter image composition methods are a traditional set of 12 methods which are very well defined. They are known as Alpha Composition as the images are merged according to some aspect of the image transparency or 'Alpha Channel'. You can find the mathematical definitions for these in the SVG Alpha Compositing document.

Here is a classical table showing the results of these 12 methods with two triangular images.
[IM Output]

The default compose method (when completely undefined) is 'Over', and is what most people normally want when composing images.

To understand, and remember what each of the above compose methods do, the resulting image would be the same as if you said...
{Source} --{compose_method}--> {background}

That is, the resulting image for method 'ATop' is equivalent to "the overlay image 'ATop' of the background image". Meaning, the background image will keep its 'shape' but the colors of the source image will sit 'on top' of the background.

However remember the image order is reversed when using the "convert -composite" operator. In that case it is 'last_overlay_image' OP 'older_background_image'.

These 12 methods define not only which of the two images are 'visible' in the result, but also how it affects the part of the image which is NOT overlaid by the source image. That is, whether the original 'background' is left as is or completely cleared. I purposefully made the 'destination' image in the above table larger so that you can see if the rest of the image was cleared or not.

These 'clearing' methods are: 'Src', 'In', 'Dst_In', 'Out', 'Dst_ATop', and 'Clear'. There is a special expert setting that can be used to turn this normal effect off. See the special 'Copy' compose method below, which is a special '13th' method which IM provides.

ImageMagick version 5 and before did not clear any area not overlaid by the source image. This was incorrect handling of the Duff-Porter Composition operators, and was corrected during IM v6 development.

Lastly, the Duff-Porter Alpha Composition methods never make 'transparent colors' visible. This is important as a transparent part of the image has an undefined color which could be ANY color. See Controling Image Transparency for details about 'transparent colors'.

This is why Duff-Porter composition is often the preferred masking method unlike 'CopyOpacity' whcih completely replaces the Alpha Channel of an image and can make the invisible visible.

Over (overlay image over background)

This is the default compose method, the one everyone thinks of when overlaying an image on top of another image. The overlay image is placed 'over' the background image in the same way as an 'animation cell' or 'overhead transparency' can be placed over a background scene or image.

It is so common that I doubt I really need to say much more. So lets present a example of overlaying a single letter image over a background image.

  convert -background none  -fill white \
          -font Ravie  -pointsize 36   label:A   label_A_white.png
  composite -gravity center label_A_white.png   rose:   compose_over.gif
[IM Output]
[IM Output]

The overlay can be centered with gravity as above, or positioned exactly using a "-geometry" setting. If it is positioned outside the bounds of the background it will be clipped, or ignored, as appropriate.

In this example, the image is overlaid using the "convert -composite" operator, but positioned half way above the background. Note the reversal of the image order.

  convert  rose:   label_A_white.png \
          -geometry +5-15   -composite   convert_over.gif
[IM Output]

Dst_Over (put image 'under' background)

Like other 'Dst_' methods, this works like the 'Src_' version of the method (just remove the "Dst" from the method name), but with the overlay and background images swapped. As such 'Dst_Over' is equivalent to placing the source overlay image 'under' the destination. The result is that only the parts of our source or overlay image not hidden by the destination or background image will be visible as they peek out from underneath.

This is NOT exactly the same as 'Over' with argument images swapped, as the size, positioning and other image meta-data, still comes from the background or destination image. The output image size is the same as the 'background' image.

For example, here we overlay a black A label 'under' our original white A. We can reposition the black A, relative to the white A background. As you can see this is great for adding a hard shadow, without needing to worry about expanding the image size.

  convert -background none  -fill black \
          -font Ravie  -pointsize 36   label:A   label_A_black.png
  composite -compose Dst_Over  -geometry +5+5 \
          label_A_black.png  label_A_white.png   compose_under.png
[IM Output]
[IM Output]

The important thing to note is that the size of the background is preserved while the overlay's position, relative to the background, can be modified and is clipped by the background. This is what makes this operator such an important and useful operator.

The "-tile" setting of "composite" also makes this form of 'over' very useful as a way to tile underneath an image. For example, tile the built in checkerboard pattern underneath the shadowed letter we just created.

  composite  -compose Dst_Over -tile pattern:checkerboard \
             compose_under.png   compose_under_tiled.jpg
[IM Output]

Src ('crop' to background image dimensions)

This operator completely replaces the background image with the overlay image. The colors and transparency in the background are completely junked leaving a blank image the same size as the original destination over which is applied the source image.

But what good is that? Well, two things.

First, you are effectively replacing the background image with the source image but preserving all the meta-data associated with the original background image. That is, the image changes but the meta-data does not.

Second, the size of the final image does not change even though the image content does. That is, the resulting image has the same size as the original background. As such you can effectively use this operator to either crop or add a border to the source or overlay image so that it becomes the same size as the given background image (along with the background meta-data).

For example, suppose you want to make a plasma image and clip it so it is the same size at the built-in rose image. This will let you do it without needing to know just how big the rose image is.

  composite -compose Src  -size 100x100  plasma:tomato-dodgerblue \
            rose:   compose_crop.gif
[IM Output]

Of course the above is equivalent to a "-crop" of the plasma image, not a 'resize'. The original image's meta-data is also preserved.


If the overlay is smaller then the rest of the background image is replaced with transparency to fill it out. Please note however that the background must have an alpha channel, or it will fill the extra space with black (the color that 'none' or 'transparent' has without any alpha channel).

  composite -compose Src -gravity South \
            hand_point.gif   rose:   -matte   compose_expand.gif
[IM Output]
[IM Output]

Copy (copy or replace image)

This operator is not one of the 12 'Duff-Porter' compose methods which is why it was not on the chart above. It is very important nevertheless. It works exactly like the "Src" compose method, but it does not touch the background image outside the overlaid area. That is, it limits its copying abilities to just the area overlaid and nothing else.

This allows you to crop a small section of a larger image, work on the smaller image for speed, then 'copy' the results back onto the larger image without touching the other areas of that image. This in turn allows you to optimize image processing of very large images.

Here is the same example I used above, but using 'Copy' instead of 'Src', showing how IM will not waste time clearing out the rest of the background as demanded by the 'Duff-Porter' algorithm.

  composite -compose Copy -gravity South \
            hand_point.gif   rose:   -matte   compose_copy.gif
[IM Output]

This operator is also very similar to 'Over', except that the transparency of the source image is also copied, replacing the background image completely. If there is no transparency it would perform exactly like 'Over'.

Internally, it uses a special composition control setting that tells IM not to modify the parts that are not overlaid.

As of IM v6.5.3-4 this control setting can be set by the user and is known as "compose:outside-overlay". You turn it off by setting it's value to "false". For example, here is an equivelent to the "-compose Copy"...

  convert rose:  hand_point.gif -matte -gravity South \
          -set "option:compose:outside-overlay" "false" \
          -compose Src -composite    compose_copy_src.gif
[IM Output]

Dst (a 'no-op' compose)

This operator does nothing. The source, or overlay image, is completely ignored and the destination, or background image, is left unchanged.

The method's real use is as a means of 'turning off' an alpha composition operation in other image operators.

For example, we use the Frame Operator to frame our rose image (with a transparent background) but then use "-compose Dst" to prevent the image from being added to the frame. In other words, we only use the rose to set the size of the internal frame of the result. The frame, and only the frame, is the result.

  convert rose:   -matte  -mattecolor Gold  -bordercolor none \
          -compose Dst   -frame 7x7+3+2   compose_frame_dst.gif
[IM Output]

The "-matte" operator assures an Alpha Channel is available or you will end up with a black middle rather than a transparent one. The "-bordercolor" defines the color inside the frame which is usually placed underneath the source image.

The 'Dst' method can also be useful in a script to disable an alpha composition in a large an complex command without needing to create two different IM commands.

Dst_In (or 'mask' the background with source)

The 'Dst_In' method is like using the source image as a 'Copy_Opacity' mask for the background image. It will remove the overlay image's shape from the background image like a cookie cutter which cuts out a cookie's shape from cookie dough.

For example, let's use the fancy 'A' from above as a mask to cut out its shape from the rose image.


  composite -compose Dst_In  -gravity center \
            label_A_white.png  rose: -matte  compose_mask.png
[IM Output]

Unlike the 'Copy_Opacity' method you can NOT use a greyscale image as the mask as only the overlay image's alpha channel is used in this operation. Any color in the overlay is completely ignored.

Dst_Out (or a 'erase' operation)

Using the 'cookie dough' metaphor of 'Dst_In' the result of the 'Dst_Out' method is the dough that was left behind once a cookie has been cut out.

It can be used to cut holes, or take bites out of the background image, using the shape of the overlay. Any color in the overlay is again completely ignored.


  composite -compose Dst_Out  -gravity center \
            label_A_white.png  rose: -matte  compose_erase.png
[IM Output]

The mathematical formulae of these two compose methods are designed explicitly so that if you use 'Dst_In' and 'Dst_Out' on the same set of images, you can fit them back together (using 'Plus' method) just like a jigsaw puzzle.

For example here we 'add' (using 'Plus' composition) the last two images we generated above. This image is exactly the same (to the pixel) as the original 'rose:' image.

  composite -compose Plus  compose_mask.png  compose_erase.png \
            compose_rejoin.png
[IM Output]

Erasing part of an image is not an easy task in any graphics program. For example a "-draw" operation can only add color to an image. It will not remove color once it has been applied to your canvas. Think of a painter who is painting some advertising on a glass door or window. He, or she, can add paint, but can't remove paint, by painting over it.

By drawing the shape you want to erase onto a transparent canvas, you can then use 'Dst_Out' to remove it from your working image. It's a bit like our painter carefully wiping off wet paint with a specially shaped rag. The shape can be used to remove all or some of the color making it either fully or semi-transparent.

For example, suppose you want to draw a crescent moon symbol on a transparent canvas. This alpha composition method makes this difficult shape easy to draw by overlaying two circles.

  convert -size 70x70 xc:none -fill white -draw 'circle 35,35 35,5' \
          \( -size 70x70 xc:none -fill black -draw 'circle 28,30 35,5' \) \
          -matte -compose Dst_Out  -composite   moon_crescent.png
[IM Output]

The second image must be created and drawn in parenthesis. If you don't you will find that "-draw" will draw onto BOTH the overlay image AND your original background which is obviously wrong.

If you did not use parentheses you will find a circle of semi-transparent black pixels around the erased part of the image. I know, it happened to me while creating this example much to my own annoyance.

ATop ('Over', but clip to background image)

Like 'Over' but limit the result to the original shape of the background image. In other words, the alpha channel on the destination is unchanged but the image colors are overlaid by any non-transparent parts of the source image.

If the background image is fully opaque (no transparency), this operation will act exactly like the normal 'Over' composition. It only differs when the background contains transparency which also clips the overlay.

What makes this useful is for overlaying lighting and shading effects that are limited to the object (shape) of the destination.

For example, say we have a red circle and want to add a highlight as if it is a 3 dimensional ball. We can create the circle, and the highlight, then overlay the highlight using 'ATop' to limit it to the circle.

  convert -size 70x70 xc:none \
            -fill red -draw 'circle 35,35 10,30'  red_circle.png

  convert -size 70x70 xc:none -draw 'circle 35,35 35,20' \
          -negate  -channel A -blur 0x8    red_highlight.png

  composite -compose ATop -geometry -13-17 red_highlight.png \
            red_circle.png red_ball.png
[IM Output] [IM Output] [IM Output]

This is different from the 'In' or the 'Dst_In' compose methods as both images can contain a transparent shape. Only the parts which are 'above' the destination or background image is overlaid.

The creation of the white highlight was done using "-negate" to ensure the whole image is actually white. This was used to avoid a major bug in the "-blur" operator, which has now been fixed in IM version 6.2.4. See Blur with Transparency Bug for more details of this old bug.

In a similar way we can add a fuzzy shadow to our ball clipped to the boundaries of the ball itself so that it looks even more 3-D like. I'll leave it as an exercise to the reader to figure out how the following command achieves this result.

  convert  moon_crescent.png -fx 0 -channel A -blur 0x7 \
           red_ball.png  +swap -compose ATop -composite  red_ball2.png
[IM Output]

With a little more care with preparatory images the above image can be made even more realistic. For showing the usage of this compose method, it isn't bad.

Further examples of using 'ATop' compose method, can be seen in Generating 3-D Logos.

Clear (Clear the Background. Ignore overlay image)

This is an unusual compose method that essentially ignores the overlay image completely, and just clears the background image.

This makes it an ideal method of creating a transparent or black canvas, the same size as the background image, for complex projects. As the overlay image is not used, a single pixel "null:" image is a good overlay to use.

  composite -compose Clear null:  rose: -matte compose_clear.png
[IM Output]
Of course the "-matte" operator (while not needed in this case) assures the background has a matte (or alpha) channel to clear the destination image.

If you specifically turn off the matte channel you get a black canvas due to the mathematics involved.

  composite -compose Clear null:  rose: +matte compose_black.png
[IM Output]

With the special control option "compose:outside-overlay" you can limit this clearing to just the area overlaid regardless if the overlay image contains transparency or not. For example:

  convert rose:  hand_point.gif -matte -gravity South \
          -set "option:compose:outside-overlay" "false" \
          -compose Clear -composite   compose_clear_limited.gif
[IM Output]

Xor (Clear the area shared)

This is a very strange and little used composition method. It overlays two images then clears the overlapped area to transparency.

  convert -size 60x60 \
          \( xc:none -fill blue   -draw 'circle 21,39 24,57' \) \
          \( xc:none -fill red    -draw 'circle 39,39 36,57' \) \
          -compose Xor   -composite   compose_xor_2.png
[IM Output]

Things get even more interesting when a third image is xor'ed on the above result.

  convert -size 60x60  compose_xor_2.png  \
          \( xc:none -fill green  -draw 'circle 30,21 30,3'  \) \
          -compose Xor   -composite   compose_xor_3.png
[IM Output]

As you can see overlapping multiple images can produce some wonderful effects where any even number of images overlapping will be clear, while any odd number of overlapping images will result in the last image overlaid showing through.

FUTURE:  Xor effects on semi-transparent images get extremely weird.
Explore this and create an example demonstrating this weirdness.


Mathematical Compose Methods

This group of compose methods lets you perform mathematics with the images. This may not seem very useful but for low level manipulation of images the methods allow you to do things which you may not normally think of.

Unlike the previous Duff-Porter image composition methods they are generally greyscale methods. That is they are usally applied to images were either one or both images are greyscale, and usually do not contain transparency. That is not to say transparency can not be used (see Mathematical Composition and Alpha below), but it is not a very common practice.

The default usage of Math Compositions is defined by the SVG image file format specification. You can read more about them in SVG composition guide (2009), also in Pegtop Blend Modes and SimpelFilter Photoshop Blend Modes.

The special gradient image you see adjacent to each of the following operators visualizes the operator in terms of how it affects color values. The result is produced by composing two gradient images as in the following...

  convert -size 64x64 gradient:             gradient_src.png
  convert -size 64x64 gradient: -rotate 90  gradient_dst.png
  composite gradient_src.png -compose Multiply gradient_dst.png \
            gradient_result.png
[IM Output]
Source
 + [IM Output]
Dest
=> [IM Output]
Result

Basically, if you use the color value of the overlay (source) pixel vertically, and the background (destination) pixel horizontally, you can look up the value that will result from applying that operator with those values.

In the above example, you will see that 'Multiply' will generally make images darker, and that any black value (0) in either input image will produce a black result. Something that can be very useful.

[IM Output]

Multiply   ( )   (make white transparent for diagrams/text)

Is one of the more useful, but under-rated, compose methods and is a simple multiply of the two images.

Its formula is of course:   Src*Dest

This means that if one of the images is pure white, the result will be the other image. On the other hand if one image is black the result will be black. Between these extremes one image will darken the destination image by the amount given.

Note that 'Multiply' will only darken an image, it will never brighten it. That is, it 'attenuates' an image toward black, which makes this compose method a 'Burn' style of composition. (See Lighting Composition Methods below)


  convert label:Rose label_white.gif
  composite -compose Multiply -gravity center \
            label_white.gif  rose:  compose_multiply.gif
[IM Output]
[IM Output]

This method works very well in a lot of situations, but is especially good when one of the images images has black (or greyscale) lines on a mostly white background, such as text images. If both images contain regions of color, then you may get unusual results.

In other words. this technique is perfect for overlaying images and other diagrams directly onto line drawings wit ha white or very light colored background.

For example, I want to add some diagrams to a page of text which will be included in a ray-traced image. You can see this 'page of text' in the image resulting images of my Studies in Polyhedra.

Given two grey scale image masks, multiply is also a good way to erase parts of an image to black based on some mask. It does this linearly, so the mask can be a greyscale image rather than a purely Boolean on/off image. See Mathematical Composition.

Multiplying an image with itself is actually a useful technique to produce a squared darkening of an image, so bright colors remain prominent, but other colors become darker. Actually this is equivelent to a Gamma operator with a value of "0.5", or an Evaluate PowerOf operation with a value of "2.0".

For example see a Star Generator, to produce a more realistic distribution of star intensities. Or it can be used on satellite cloud images before overlaying the result on a geographical map.

[IM Output]

Screen (make black transparent for diagrams/text)

This is almost exactly like 'Multiply' except both input images are negated before the compose, and the final result is also then negated again to return the image to normal. In technical terms the two methods are 'Duals' of each other.

That makes its formula:   1-(1-Src)*(1-Dest)

This means that if one of the images is pure black, the result will be the other image. On the other hand if one image is white the result will be white. Between these extremes one image will lighten the destination image by the amount given.

Note that a 'Screen' composition will only make an image brighter, never darker. This is a style of composition known as 'Dodge' composition. (See Lighting Composition Methods below)

This composition method is perfect for overlaying white text on a black background, then onto other images...

  convert -background black -fill white label:Rose label_black.gif
  composite -compose Screen -gravity center \
            label_black.gif  rose:  compose_screen.gif
[IM Output]
[IM Output]

See Mathematical Masking for an example of using this to overlay a white shape on an image.

[IM Output]

Bumpmap (greyscale multiply)

The 'Bumpmap' method is essentially the same as 'Multiply', except that the source image is converted into grey-scale before being overlaid. In other words, it will darken the image anywhere the source image is dark.

You could think of this as a 'multiply by intensity' type operator.

For example...

  composite -compose Bumpmap -gravity SouthEast -geometry +3+3 \
            hand_point.gif   cyclops.gif   -matte   compose_bumpmap.gif
[IM Output]
Note how the "hand_point.gif" image is grayscaled before applying.

Its original purpose is to add texture (like a paper or fabric texture) to images. However as it can only darken images, it is not as useful as the 'HardLight' method which can both lighten and darken images (see below).

[IM Output]

Divide   ( )   (removing shading effects)

The destination image is divided from the source image. However as color values are always between 0.0 (black) and 1.0 (white) this will in fact brighten the source image by the amount of black that appears within the source image.

That makes its formula:   Src / Dest .
Note the order of the images, as it is very important!

Remember that the order of the images is as if you are reading the "composite" command line. That is "Src OP Dest". So this "-matte" method acts as if you are reading
" Source Divided_By Destination "
making the destination image the divisor.

However in "convert" the order is swapped so that the divisor image must be given before the numerator image! This is often inconvenient as usally you want to divide your main image by the newer modification image. That is a "+swap" is usally needed as part of the process. However this is the way the operator works.

The source will always be brightened, by the amount of darkness that exists in the destination image. If the destination image is pure white, the source image will be left unchanged (assuming both images are the same size).

Now this may sound weird but it is actually a very useful operation. It means you can effectively remove dark patches from an image caused either by lens vignetting, bad scanning, or tinting caused by age.

For example, I have an image of hand written text which was very roughly scanned (using a digital camera without flash, then reduced in size to remove digital noise). The paper has faded edges, and as a flash was not used the background is very dark, and has shading effects because the paper wasn't completely flat.

[IM Output]

Just normalizing the image to enhance the contrast of the image doesn't help to remove the edge coloring or other shading effects.

  convert text_scan.png -normalize text_scan_norm.png
[IM Output]

However by blurring the image to remove the lines, and then dividing that from the original, we effectively remove all the gross shading effects from the image.

  convert text_scan.png \( +clone -blur 0x20 \) \
          +swap -compose divide -composite  text_scan_divide.png
[IM Output]

The result is that the background color is turned white, while the thin lines of the text remain clear, though slightly 'thinner'.

As you can see it is a lot clearer than just normalizing it though some of the anti-aliasing was also removed. Some extra adjustments could have been made to the divisor image, but it is very close to what is expected.

This technique is also used in the Removal of Vignette from images.

Using smaller blurs can produce an alternative means of generating artistic outline images, such as shown in Coloring In Outline Images.

This operator could be combined with a background gradient generator, such as Sparse Color Gradients to generate better 'divisor' images, than just simply blurring the whole image.

The 'Divide' is actually the same as the 'Color_Dodge' method, but with the divisor image negated, and used as the source image. This may be easier to apply as a "+swap" is not needed, and the image meta-data of the Numerator is preserved. However you need to add a "-negate" operator.

For example the above division using 'Color_Dodge' would become...

  convert text_scan.png \( +clone -blur 0x20 -negate \) \
          -compose Color_Dodge -composite  text_scan_cdodge.png
[IM Output]

See 'Color_Dodge' for more examples.

[IM Output]

Plus   ( )   (Add colors together to form a blend)

Add the colors of the overlay to to the background. In essence causing the two images to blend together equally.

Its formula is naturally:   Src + Dest

Note however that if the added colors overflow the color limits, the color will be clipped by the normal color range limits. This is why half the image in the resulting gradient image is pure white, as these values were clipped at their maximum value. Caution is recommended to ensure that images are not clipped if that is not wanted.

The operator has a number of major uses.

Merging together images which contain separate channel colors, but where only the individual channel has color. For example...

  convert -size 60x60 xc:none -fill red \
          -draw 'circle 30,21 30,3'   compose_R.png
  convert -size 60x60 xc:none -fill lime \
          -draw 'circle 21,39 24,57'  compose_G.png
  convert -size 60x60 xc:none -fill blue \
          -draw 'circle 39,39 36,57'  compose_B.png
  composite -compose plus  compose_R.png compose_G.png  compose_plus_RG.png
  composite -compose plus  compose_R.png compose_B.png  compose_plus_RB.png
  composite -compose plus  compose_G.png compose_B.png  compose_plus_GB.png
  composite -compose plus  compose_R.png compose_plus_GB.png \
            compose_plus_RGB.png
[IM Output] [IM Output] [IM Output]
[IM Output] [IM Output] [IM Output] [IM Output]

Due to IM's compliance to the SVG standard, 'green' is not a true green color (like it is in X11 color names) but a dark or half bright green. A true RGB green can be specified with the color 'lime' as we have done in the above example.

It is also used as a mathematical operator to add together separate gradient images. For example in calculating a 'manhatten' Difference Images, or in Gradient Mathematics.

'Plus' is sometimes used to add white text to an image. This is NOT correct usage, and may result in some anti-aliasing inconsistencies. The better way is to use the 'Screen' compose method. This uses a multiplication rather than an additive method of increasing brightness.

The 'Linear Dodge' compose method is is equivelent to 'Plus', but using the 'Over' alpha blending.

That is with no transparency, these two operations are equivelent...

  convert  image1.png image2.png -compose Plus -composite result.png

  convert  image1.png image2.png -compose LinearDodge -composite result.png

This is how 'Photoshop' implements 'Plus'

Plus - Special blending Operator

What makes the '
Plus' more important is that it is one of a very few mathematical operators that implements a different blending function than 'Over' blending. It not only 'adds' the colors but it also 'adds' the alpha channel values, and is about the only operator that does this, by default

This is important as it allows for the correct joining of complementary masked images. For example, see the merging of Dst In and Out images.

It also allows you to use transparency to generate a weighted average or Blend two images together.

If it wasn't for this special blending method of 'Plus', these special transparency handling techniques would not be normaly possible.

As of IM v6.6.1-6 the ability to use the mathematical operator on alpha channels was added to all the Mathematical Compose Methods simply by removing the default 'Sync' flag from "-channel" setting, (actually just specifing the specific channels to apply it to). See Image Channel Mathematics using Image Composition below.

This means the 'Plus' the only Mathematical Compose Methods operator not effected by this feature as it already apply it by default.

[IM Output]

ModulusAdd

The 'ModulusAdd' is much like the 'Plus' except when the result exceeds white, it is wrapped (modulus) back to black.

For example, if we add two grayscale gradients the brightest colors will wrap to form a second gradient.

  convert -size 60x60 gradient:    gradient.png
  composite  gradient.png gradient.png -compose ModulusAdd  compose_add.png
[IM Output]

This modulus type of composition can be used to produce some very interesting gradients such as.

  composite gradient.png \( gradient.png -rotate -90 \) \
            -compose ModulusAdd   gradient_diagonal.png
[IM Output]

And multiple modulus additions can make venetian blind type repeated gradients.

  convert gradient.png \( +clone +clone +clone +clone \) \
          -background gray50 -compose ModulusAdd -flatten  gradient_venetian.png
[IM Output]

Which produces a gradient repeated 5 times. Note how I use a background of 'gray50' to effectively 'roll' the gradient half a modulus cycle forward.

[IM Output]

Minus   ( )

This is a mathematical oddity in the math compose methods. The result is one image subtracted from the other.

Its formula is:   Src - Dest

For example, subtract a circle from the final result of the 'Plus' operation above.

  composite -compose minus  compose_plus_RGB.png  compose_R.png \
            compose_minus.png
[IM Output]

The 'Linear Burn' compose method is also used for color subtraction, but works by the user negating the image to be subtracted.

That is, with no transparency, these two operations are equivelent...

  convert  image1.png image2.png -compose minus -composite result.png

  convert  image1.png -negate image2.png \
                            -compose linear_burn -composite result.png
With the first image being subtracted from the second.

This is how 'Photoshop' implements 'Minus'

[IM Output]

ModulusSubtract

The 'ModulusSubtract' operator is the same as 'Minus' except that it is a modulus subtraction. Subtrating 'white' from 'gray' will result in the original 'gray', and not black, as the values wrap back around.

A side effect of subtracting the transparency channel will also have wierd effects resulting in different parts of the image being made transparent and opaque in a seemingly uncontrolled way.

  composite -compose subtract  compose_plus_RGB.png  compose_R.png \
            compose_subtract.png
[IM Output]

[IM Output]

Difference (image compare, and selective negate)

The resulting image is the absolute difference in the color values.

Its formula is:   abs(Src - Dest)

The 'black' and 'white' difference will produce a maximum result of white while any colors which are the same will produce black. Basically a simple form of image comparison.

The more common use of this composite method is for comparing two images of the same size to see how they differ, and even produce a percentage of that difference.

This operator is typically used to generate Comparison Difference Images.

The operator also can be used to selectively negate an image. Overlaying black has no effect on the background, while overlaying white negates the colors in the image at that location.

For example lets negate half the rose image.

  convert -size 2x1 pattern:gray50  -scale 70x50\! black_n_white.gif
  composite black_n_white.gif   rose: \
            -gravity center -compose difference   compose_negate.gif
[IM Output]
[IM Output]


[IM Output]

Exclusion (image difference excluding greys)

Its formula is:   Src + Dest - 2*Src*Dest

This is sort of an averaged difference. White on white will produce black (no difference), the same with black on black. However grey on grey will produce a grey result. White and black naturally still produce white (maximum difference).

Another way of looking at this is that bright image regions cause inversion to the respective other layer. Very dark regions change nothing at all. In this manner the Exclusion method is the same as 'Difference' (see previous).

One use for this operator is to multiply 'biased gradients' such as used for Displacement Maps. These are gradients where a 50% gray value is thought of as being 'zero' with darker colors representing a 'negative' value, and lighter colors representing a 'positive' value, with the values ranging from -1 to +1. See Multiply Biased Gradients, for details.

Another use of this compose method, submitted by Joe Fry, is a way to merge multiple difference images together. The final image shows the changes of all the images, not just between two images. That is, given images A, B and C, first generate the difference images for A, B and B, C then use exclusion on those results so that you get one image showing how all three images changed.

This method is also closely related to how the Xor composition blending operator handles the alpha transparency values.

[IM Output] [IM Output]

Lighten and Darken (select color based on brightness)

Compare the source and destination image color values and take the respective lighter or darker value.

The formula for Lighten is:     If Src > Dest   then   Src
  else   Dest
For darker, invert the result of the comparison.

A typical use of 'Lighten' is to compose a blurred version of the original image so that the 'highlights' in the original image get a soft glow about them, while dark parts are not similarly blurred. For one example see Polar Distortion Tricks.

Example needed...

Unfortunately these operators work on each RGB channel separately, and as such this could result in some color distortion.

To avoid this color distortion problem, you should probably select the lighter/darker color based on overall color intensity.

Specifically, create a gray-scale image of the two images and 'Lighten' or 'Darken' them as appropriate, You can now use a 'Change_Mask' to compare that result with one of the gray-scale images used for this comparison. This 'mask' then be used to select which color comes from which of the original colored images.

Note that "Gimp", "Photoshop", "PhotoLine", "Paint Shop Pro", all compare channels directly just like IM. However "Photo-Paint" compares the images by color intensity, and uses that to decide which image to select colors from, thus preserving color integrity. On the other hand "Picture Publisher", and "PhotoImpact" use the color lightness (as defined by the HSL colorspace) for the comparison.

Set Theory Equivelent Operations

A number of the mathematical methods above are also used to perform set theory or boolean operations with shapes.

The 'Lighten'compose method can be used to find the 'Union' or the Boolean 'Or' of two (or more) groups (sets) or pixels.

  convert -size 64x64 xc: -draw 'circle 22,32 5,32'  -negate circle_left.gif
  convert -size 64x64 xc: -draw 'circle 41,32 58,32' -negate circle_right.gif
  convert circle_left.gif circle_right.gif \
          -compose Lighten -composite    circle_union.gif
[IM Output] u [IM Output] => [IM Output]

The 'Darken' compose method produces an 'Intersection' or a Boolean 'And' of the pixels.

  convert circle_left.gif circle_right.gif \
          -compose Darken -composite    circle_intersection.gif
[IM Output] n [IM Output] => [IM Output]

The 'Difference' compose method produces an 'Exclusive OR', also known as a 'XOR of the two sets.

  convert circle_left.gif circle_right.gif \
          -compose Difference -composite    circle_disjunction.gif
[IM Output] (+) [IM Output] => [IM Output]

An 'Exclusion' method could also have been used for this purpose, though handles greyscale (non-boolean) values differentally. It is however the method used for 'XOR' alpha blending.

And lastly 'Minus' can be used to generate the 'Relative Complement' of two sets of pixels. That is the pixels in the source that is not in the destination.

  convert circle_left.gif circle_right.gif \
          +swap -compose Minus -composite    circle_complement.gif
[IM Output] - [IM Output] => [IM Output]

The "+swap" in the above is needed so that you get a 'source - destination' ordering of the images. Remember it is the destination that is subtracted, not the source. :-(

FUTURE: a swapped minus is probably needed for proper multi-image layered subtraction of images. That is a method to subtract the source from the destination.

Note that a "-clamp" may be needed for HDRI versions of ImageMagick when doing the above, to prevent the generation of negative values.

Mathematical Composition and Alpha Blending

You can use the above mathematical composition methods for performing mathematical operations on image. However their is on major cave-at with this. You can not use it in this way with images containing transparency.

By default all the above mathematical compositons follow a convention defined by the SVG specification. SVG composition guide (2009).

What this means is that if you try to use mathematical compositions on images with an alpha channel (that is some form of transparency), you will may not get a true mathematical composition, but a 'blended' form of composition. For example, here I create gradient images with some transparency around them. I then 'Multiply' them together.

  convert -size 64x64 xc:none -draw 'rectangle 20,0 43,63' \
          gradient: -compose In -composite    alpha_src.png
  convert alpha_src.png -transverse     alpha_dst.png
  convert alpha_dst.png  alpha_src.png \
          -compose Multiply -composite  alpha_result.png
[IM Output]
Source
 + [IM Output]
Dest
=> [IM Output]
Result

Note that the parts of the images that did not overlap was just simply included into the resulting image, as is, without modification. That is the images were 'blended together'. Worst still if the image contain partial transparencies, all the colors within the image will be 'weighted' by the alpha channel.

Image Channel Mathematics using Image Composition

If the image you are using a Mathematical Compose Methods on are simply fully-opaque gray-scale images, then you can use the above methods on them directly, without any problems.

However by default the compose methods will be applied to all the color channels, with alpha blending, just as you saw above. This make applying them to just a specific channel or to do some image mathematics on just the alpha channel difficult.

As of IM v6.6.1-6 the Mathematical Compose Methods were modified so that if you give a "-channel" setting without the 'Sync' (enabled by default), the normal 'SVG' defination for the compose methods are relaxed.

The 'Sync' "-channel" flag, effectually means, "syncronise the color and alpha channel operations". By default the "-channel" setting is set to 'RGBK,Sync', so by default the mathematical compose methods follow the SVG defintion.

If you remove the flag by just specifying specific channels to work with, then the Mathematical Compose Methods will be applied to the specified individual image channel, completely independantally of each other. This not only includes removing any 'alpha-blending' that can 'weigh' the color values, but also means you can apply that mathematical composition methods directly to the alpha channel as well.

For example here I 'Multiply' two images containing a transparent gradient. But I did not modify the "-channel" setting.

  convert -size 64x64 gradient:black-none   alpha_grad_src.png
  convert alpha_grad_src.png -transverse   alpha_grad_dst.png
  convert alpha_grad_dst.png  alpha_grad_src.png \
          -compose Multiply -composite  alpha_grad_result.png
[IM Output]
Source
 + [IM Output]
Dest
=> [IM Output]
Result

Note that multiplying 'Black' with 'Black' is 'black', so the color does not change in this example.

However the result is definatally not a multiplication of the images alpha channel values. The result should be mostly transparent (low alpha values). Instead you get a 'over' alpha-blending (which is actually equivelent to a mathematical 'Screen' composition of the alpha channel).

But if I repeat the same operation after removing the default 'Sync' flag from the "-channel" setting, and adding the 'A' or 'Alpha' channel flag, then I can correctly multiply the alpha channel.

  convert alpha_grad_dst.png  alpha_grad_src.png \
          -channel RGBA  -compose Multiply -composite  alpha_grad_nosync.png
[IM Output]

Remember the default "-channel" setting is 'RGBK,Sync' ('Alpha' is not actually set). The presence of the 'Sync' flag causes compose to ignore all other "-channel" settings, and follow the normal SVG definition of the composite settings.

To allow the Mathematical Compose Methods methods to be used strictly as channel 'maths' operators, you need to remove the 'Sync' flag, and define exactly what channels you want mathematical compositions to be applied to.

All this only applies to Mathematical Compose Methods (as detailed above) as well as the special 'Mathematics' compose method (see below). In the future it could be expanded to other composition methods such as Lighting Composition Methods, if users request it.

For more information on using image mathematics, see Mathematics on Gradients. More specifically those examples look at using mathematical compositions for generating 'Biased Gradient Images, which is bit more involved.


Lighting Composition Methods -- Light, Dodge, Burn

These methods modify the colors of an image in highly complex ways and are typically used to adjust the shade or intensity of the image making some areas brighter and others darker. One of the images is usually a grayscale overlay.

These fall into three sub-catagories of related operators.
'Burn', which generally darkens images. (like 'Multiply')
'Dodge', which generally brightens images. (like 'Screen')
'Light', which both darkens and lightens images based on the the darkness and brightness of one of the images.

Generally one of the images will consist of either a color pattern or photo, while the other is a grey-scale image that is being used to brighten or darken the image appropriately. Which image should be the color, and which gray-scale, is debatable and depends on how the method was implemented. There is no standard in this regard.

As a consequence, many users do not understand or miss-use the operators. Also a guide on correctly using these compose methods is practically non-existant.

[IM Output]

Overlay (add color to a greyscale object)

This compose method is very unusual in that it has been designed to both 'Multiply' (darken) and 'Screen' (lighten) at the same time. Which method chosen is selected by a 50% cut-over.

Its formula is:     If Dest <= 0.5   then   2*Src*Dest
  else   1-2*(1-Src)*(1-Dest)

The result is a special compose method which preserves any pure white and black (highlights) that is present in the destination image while tinting the mid-tone greys of that mage by the colors found in the overlay image.

That is, given a grey-scale image as the destination, this operator will color that background using the source image preserving any shadow and highlighting effects that are present in the destination.


  convert -size 64x64 gradient:yellow-blue gradient_yell-blue.jpg
  convert -size 64x64 gradient: -rotate 90 gradient_grey.jpg

  convert gradient_grey.jpg   gradient_yell-blue.jpg \
          -compose Overlay  -composite   compose_overlay_gradients.jpg
[IM Output]
Dest
 + [IM Output]
Overlay
=> [IM Output]
Result

As you can see the mid-tone grays of the gradient image was colored with the colors of the image provided.

This method, unlike 'Multiply' or 'Screen', is not associative.

  convert gradient_yell-blue.jpg  gradient_grey.jpg \
          -compose Overlay   -composite   compose_overlay_gradients2.jpg
[IM Output]
Dest
 + [IM Output]
Overlay
=> [IM Output]
Result

This 'overlaying color' into a image of grey highlights is makes this method perfect for adding color to the output of the "-shade" operator. However you need to be very careful to generate a perfect mid-tone grey from that operator, to get correct coloring on areas without any highlights. See Shade Overlay Highlights for details.

For example, given a circle we can shade it to produce 3 dimensional effects then tint the result with the original image to restore the original colors.

  convert -size 64x64  xc:dodgerblue \
          -draw 'fill skyblue   circle 32,32 7,27'  circle_blue.jpg
  convert circle_blue.jpg -shade 120x30 -auto-level circle_shaded.jpg
  convert circle_shaded.jpg  circle_blue.jpg \
            -compose Overlay    circle_shaded_tinted.jpg
[IM Output]
Dest
 + [IM Output]
Overlay
=> [IM Output]
Result

For a more practical example of using the 'Overlay' method see the "levels_3d" image on the Background Generator Examples page.

The biggest problem with this compose method is that any transparency in either image will not be preserved. That is, what is visible in either image will be visible in the result.

As overlays using this method generally have no transparency, it usually means you may need to do some extra steps to restore the transparency of the destination or background image. For examples of doing this see Overlay Color Tinting. Or a more practical but complex example in the Better 3-D Logo Generation example.

FUTURE: Add an example of 'overlaying' a shaped image here.

Up until IM version 6.1.6 the 'Overlay' compose method was broken in that it would only produce pure black or white results (most likely you would only get a pure black result). Consequently most IM users had little chance of understanding this operator. now that this have been fixed users will now be able to make good use of this method.

[IM Output]

Hard_Light (add texture or highlight/shadow to an image)

This is the same as 'Overlay' except the source and destination images are swapped. If you compare the gradient image for thei operator you can see that the gradient is diagonally transposed, showing the swap of the source and destination inputs.

Its formula is:     If Src <= 0.5   then   2*Src*Dest
  else   1-2*(1-Src)*(1-Dest)

So while 'Overlay' can add color to a gray-scale shaded object, 'Hard_Light' adds gray-scale lighting effects to an image.

For example here I generate a 'lighting effect' using a blurred "-raise" operation of a pure gray image the same size as the original. This is then composed using 'Hard_Light' to add those lighting effects to the image.

  convert rose: -fill gray50 -colorize 100% \
          -raise 4 -normalize -blur 0x4  lighting_effect.png
  convert rose: lighting_effect.png \
          -compose hardlight -composite  compose_hardlight.png
[IM Output]
Dest
 + [IM Output]
Overlay
=> [IM Output]
Result

This method makes adding both highlights (like a reflected light) or dark shadow effects to an existing image, using the one operation easy.

Here is an example of direct adding lighting 'texture' to an image.

  convert rose: \( granite: -blur 0x.5 -normalize \) \
          -compose hardlight -composite compose_texture.png
[IM Output]

Note how strong the resulting text is, almost swamping the original image with light and dark areas. this is the disadvantage of using 'Hard_Light'.

To combat this you may like to mute the contrast of an overlaid texture.

  convert rose: \
          \( granite: -blur 0x.5 -normalize  +level 30,70%  \) \
          -compose hardlight -composite compose_texture_muted.png
[IM Output]

Other lighting compose methods, such as 'Soft_Light' may also produce better results more directly.

For a better example see Overlying a Texture in the Photo Cookbook. A real life example in using 'Hard_Light' shading is provided an IM Discussion Forums on the generation of 3D DVD covers from flat source images.

Remember that both 'Overlay' and 'Hard_Light' shading are essentially the same composition method. The only difference is the images order.

[IM Output]

Soft_Light (softer highlighting of an image)

The 'Soft_Light' compose method will also add highlights and shadows to an existing color image. However, the colors of the destination image are modified to produce a softer contrast.

It is more closely related to the Overlay composition than to Hardlight. Whether this is intentional or not is unknown but it means you are better off composing the main image onto the shading image rather than vise-versa. :-(

WARNING: This lighting effect defined more like 'Overlay' rather than 'Hardlight'. That means the destination image should contain the greyscale lighting image, and the source image should contain color image.

For example here is the 'Soft_Light' texture mapping.

  convert rose:   \( granite: -blur 0x.5 -normalize \) \
          -compose softlight -composite compose_softlight.jpg
[IM Output]

As you can see, even with a normalized "granite:" image, the color changes are softer and less intensive than that of 'Hard_Light', or even 'Overlay'. However you also will never get any pure black shadow or pure white highlights, added to the resulting image.

Basically 'Soft_Light' has a softer texturing effect, which preserves the original coloring of the source image.

Here I show the color changes achieved as a result of using pure black, white and a perfect-gray color overlays.

  convert -size 1x3 gradient: -rotate 90 -scale 70x46\! grayscale_3.gif
  composite grayscale_3.gif  rose: -compose softlight  compose_softlight_2.gif
[IM Output]
[IM Output]

If you had done this with 'Hard_Light' the sides of the image would be pure black and white, rather than just a 50% darkening or brightening.

Before IM v6.5.4-3 'Soft_Light' did not work as expected, producing a brightening for any non-gray shade image overlay. In actual fact I confirmed that it was implemented correctly according to the offical 2004 SVG specification.

Unfortunatelly, it was the specification, not the implementation, that was incorrect. It was fixed in the March 2009 SVG specification. As such for IM v6.5.4-3 and later this operator now works as you would expect a light shading operator to work.

[IM Output]

Pegtop_Light (a smoother variation to soft light)

While 'Soft_Light' is much smoother than either 'Hard_Light' or 'Overlay', it is still actually based on two separate functions joined together. The 'Pegtop_Light' method produces a near identical result as 'Soft_Light' but uses a single smooth function without any discontinuity, not even the minor hard to see one used in 'Soft_Light'. Because of this it is actually much simpler and faster.

Its formula is:   2*Src*Dest + Src2*(1 - 2*Dest)

For details see the Pegtop SoftLight Alternative page.

WARNING: This lighting effect defined more like 'Overlay' rather than 'Hardlight'. That means the destination image should contain the greyscale lighting image, and the source image should contain color image.

The 'Pegtop_Light' compose method was added to IM version 6.5.4-3.

[IM Output]

Pin_Light

The 'Pin_Light' function is designed to better preserve the mid-tones of the destination image, restricting its shading to the lighter and darker overlay shading. Supposedly this simulates the harsh and sharp lighting changes that result from a tiny pinhole light source, rather than a more diffuse 'softer' light source.

Its formula is:     If Dest < 2*Src-1   then   2*Src - 1
elif   Dest > 2*Src   then   Dest
  else   2*Src

The 'Pin_Light' compose method was added to IM version 6.5.4-3.

[IM Output]

Linear_Light (A very simple but strong shading scheme)

Another image shading method that is very sensitive to the overlayed shading image. It has much larger zones of pure black and white limits.

Its formula is:   2*Src + Dest - 1

While it is a continuious function, it could really be considered a combination of 'LinearDodge' (equivelent to a 'Plus' composition) and 'LinearBurn' (which is an offset 'plus' sometimes used to subtract images).

Before IM v6.5.4-3 'Linear_Light' was proved to be incorrectly implemented.

[IM Output]

Vivid_Light (a varient of Linear Light)

The 'Vivid_Light' method is the same as that implemented in Photoshop 7, and is basically a minor refinement on the 'Linear_Light' method. What it does is avoid shading the extremes, so as to make strong primary colors in the images more 'vivid'.

Its formula is:     If Src <= 0.5   then   1-(1-Dest)/(2*Src)
  else   Dest/(2*(1-Src))

The 'Vivid_Light' compose method was added to IM version 6.5.4-3.

[IM Output]

Linear_Dodge (Photoshop 'Add' Compose)

If you compare the gradient image (right) for 'Linear Dodge' with that of 'Plus' you will find that for two opaque images they have the exact same effect. However the two operators differer in how they handle semi-transparency. For details see Plus Blending.

Its formula is of course:   Src + Dest

That is, with no transparency, these two commands are equivelent...

  convert  image1.png image2.png -compose Plus -composite result.png

  convert  image1.png image2.png -compose LinearDodge -composite result.png

The method is equivalent to the Photoshop composition mode of the same name.

The 'Linear_Dodge' compose method was added to IM version 6.5.4-3.

[IM Output]

Linear_Burn (A Photoshop 'Subtract' method)

The 'Linear Burn' compose method is an 'Add Minus One' composition, that produces the same result as if you negated all the input and output images of a 'Linear Dodge' or 'Plus' compose method.

Its formula is: Src + Dest - 1

In Photoshop this is not only known as 'Linear Burn' but also as 'Subtract'. That is because if you Negate one of the input images (such as the source image), that image is subtracted from the other image.
(1-Src) + Dest - 1 ==> Dest - Src

With no transparency these two commands are equivalent...

  convert  image1.png image2.png -compose minus -composite result.png

  convert  image1.png -negate image2.png \
                            -compose linear_burn -composite result.png
With the first image being subtracted from the second.

Basically whatever image is negated, that is the image that will be subtracted from the other. In many ways it makes it more versatile.

The 'Linear_Burn' compose method was added to IM version 6.5.4-3.

[IM Output]

Color_Dodge (protect from light exposure)

This composition method uses the source overlay image as a mask that sort of protects the background image from "light exposure" over long periods of time. The parts exposed to a lighter mask is made lighter, (or dodged), while black areas produce no change.

You could think of it as placing an object on top of an photo for a very long time, causing the parts exposed to light to slowly whiten with age, while the parts that were covered remain as they were.

A pure black overlay does not change the image while a pure white overlay will make all the background colors white, except for those that were pure black.

Its formula is: Dest / (1-Src)

In actual fact 'ColorDodge' and 'Divide' can produce the same results, though they require the image being used as a 'divisor' to be negated, and used as a 'source' image instead of as a 'destination' image. This can make 'ColorDodge' a useful alternative method of dividing images.

For example...

  convert image_A    image_B            -compose Divide     -composite image_C
  convert image_B \( image_A -negate \) -compose ColorDodge -composite image_C
Here "image_B" is being divided by "image_A" to generate "image_C".

See 'Divide' for an example of using 'ColorDodge' as a divisor, and for background gradient removal.

[IM Output]

Color_Burn (protect from light exposure)

This is the reverse of 'Color_Dodge', equivalent to inverting all the input and output images. The result is that the background image is darkened by a dark masking image, while white produces no darkening.

Its formula is: 1 - ( (1-Dest) / Src)

This operator can also be used to 'Divide' two images.

  convert image_A    image_B      -compose Divide    -composite     image_C
  convert image_B -negate image_A -compose ColorBurn -composite -negate image_C
Here "image_B" is being divided by "image_A" to generate "image_C".

One use of 'Color_Burn' is to clean dark gradient backgrounds to pure black. Much like 'Color_Dodge' can divide backgrounds to white.

Before IM v6.5.4-3 'Color_Burn' was proved to be incorrectly implemented.


Channel Copying Methods

These image composition methods are designed to transfer image channel information from one image to another. It however makes some assumptions about the image from which the 'channel' is being copied. I suggest you read the sections Image Color Space and Color Channel Operators to understand how IM represents image color channels in memory before using them.

The most useful channel copying composition methods is 'Copy_Opacity' (see below). It is about the only way to simply replace (or add) just the alpha channel to an existing image using a separate greyscale mask image.

Copy_Opacity (Set transparency from gray-scale mask)

The original purpose of the 'Copy_Opacity' operator was to copy the transparency channel of the source image into the destination image, to set that image's transparent parts. This is more commonly done using Duff-Porter operators, which are specifically designed for compositing images with alpha transparencies.

For example, if the destination is fully-opaque, which is typical of this operator's use, then either 'Dst_In', or even 'Dst_ATop' operators will achieve the same result.

So why is the 'Copy_Opacity' operator so important, when their are alternatives?

The answer is how this operator handles a special case. When the overlay (source) image has no matte (alpha or matte) channel, then this operator will treat it as a simple grey-scale image mask. That is, it will replace any existing alpha channel (actually a negated matte channel) of the image with the greyscale image given.

In summary anything that is black in the gray-scale image will be thought to be fully transparent, and white fully-opaque.

This is so important, and so commonly used, I will make it a rule of thumb...
Images using this operator should NOT contain any alpha channel.

You can ensure that the images do not have any alpha channel by always using a "-alpha Off" method, or using the older less clear plus form of the "+matte" operator, on both input images before compositing using 'Copy_Opacity'.

For example, make a grey scale moon image (which is easy to draw), then use it as a mask for a blue plasma gradient, to produce a nice mottled looking blue moon.

  convert -size 70x70 xc:black -fill white -draw 'circle 35,35 35,5' \
                               -fill black -draw 'circle 28,30 35,5' \
          moon_mask.gif
  convert -size 70x70 plasma:white-dodgerblue  moon_mask.gif \
          -alpha Off  -compose Copy_Opacity   -composite  moon_gradient.png
[IM Output]
[IM Output]

If your images have transparent components that you need to preserve, then this is not the Alpha Composition operator you need. More than likely you want to use 'Dst_In' instead, to subtract the transparent areas of the source overlay from your destination (in which case both images need to have an alpha channel enabled and used.

This operator is explained in even more detail in Using a Mask Image with Fonts and in Channels - Erasing Parts of an Image. It is also used in many other examples throughout these pages.

Copy_Red, Copy_Green, Copy_Blue

Copy the given color channel of the source image into the destination image.

As a gray-scale RGB image has the same data in all three color channels, these methods can be thought of as copying a greyscale channel image to replace the specified channel in the destination image. Much as the 'Copy_Opacity' (see above) can replace the 'alpha channel' of an image with a greyscale image.

These channel copying methods are rarely used today thanks to the use of various Color Channel Operators to separate out and re-combine color channels via grayscale channel images.

Note that when merging various grayscale gradient patterns very interesting color images can be generated using these operators. For some examples look at the color gradient combinations in raw compose operator tables.

Copy_Cyan, Copy_Magenta, Copy_Yellow

These are synonyms for the same methods in the previous section.

Basically as the 'Red' Channel in RGB images is also used as the 'Cyan' channel in the CYMK images. The same for 'Green' and 'Magenta' channels, and the 'Blue' and 'Yellow' channels.

Because of this copying the 'Cyan' channel is the same as copying a 'Red' channel. What type of channel the image data is representing depends on the Color Space of the image in memory.

Copy_Black

This also just copies the 'Black' channel from source to the destination, if it exists. However that channel only exists for CMYK images.

If the 'Black' channel does not exist this does nothing, which is probably a bug. What it probably should do is copy a grey-scale 'Black' channel image, to the black channel of the destination image (assuming that it exists).

Hue (copy the hue of a RGB image to destination)

This operator copies the hue H of the source image to replace the hue of the destination image, leaving the backgrounds saturation S and luminance L (OR is it luminance Y?) unchanged.

This assumes both images are in RGB colorspace image. I have not tested this with a non-RGB colorspace image.

Saturate (copy the saturation of a RGB image to destination)

Copies the Saturation S from source to destination, (assuming the image is a RGB colorspace image) leaving the color hue H and luminance L (OR is it luminance Y?) unchanged.

This assumes both images are in RGB colorspace image. I have not tested this with a non-RGB colorspace image.

Luminize (copy the luminance of a RGB image to destination)

Copies the luminance L (OR is it luminance Y?) from source to destination, leaving the color hue H and saturation S unchanged.

This assumes both images are stored using RGB colorspace. I have not tested this with a non-RGB colorspace image.

Colorize (copy the color hue and saturation to destination)

Copies the hue H and saturation S from source to destination, leaving the color luminance L (OR is it luminance Y?) unchanged.

This assumes both images are stored using RGB colorspace. I have not tested this with a non-RGB colorspace image.


Dissolve One Image Over Another

What the "-dissolve" operator does is provide a controlled 'Over' compose method. It adjusts the transparency of the overlay image, before it is overlaid on top of the the background, according to the percentages given.


    composite -dissolve {percent} overlay  bgnd  result


composite -dissolve {src_percent}x{dst_percent} overlay bgnd result

convert bgnd overlay -compose dissolve \
    -set "option:compose:args" {src_percent},{dst_percent} \
    -composite result
Providing two arguments (new to IM v6), allows you to exactly define how much of both the overlay and the background image is dissolved before the images are overlaid.

If only a single percentage argument is given, only the overlay is dissolved to leave that amount, (0 percent is completely transparent, 100 source is unchanged) before being overlaid (using the 'Over' compose method) onto the background. Furthermore, if you continue past a value of 100% (also new for IM v6), it will then start to dissolve away the background image.

In other words, in the 0 to 100 percent range, the background image is not dissolved at all (with a dst_percent of 100%), while in the 100 to 200 range, the overlay is left as is, (src_percent set to 100%), and the background is dissolved, so it is completely gone when the argument reaches a value of 200%).

Here is a table of results with various dissolve arguments...

  composite -dissolve {argument}  -gravity South \
            star.gif   dragon_sm.gif -matte   {result}
[IM Output] [IM Output]
[IM Output]

As you can see "-dissolve" will first slow dissolve a new image over the background, then slowly dissolve away the original background image. Which is very suitable for images containing transparent areas. You can also control the dissolve of the background, so while one image dissolves on top, you can arrange for the background to dissolve away underneath.

This is very good, but is not really suitable for a proper slide show style of dissolve between images. As one image is overlaid the images are not merged together equally, and swapping the image arguments (and corresponding dissolve arguments) will produce different results.

For the 100% to 200% range, or the second percentage argument to work, the background image must contain an alpha channel. This is especially important for JPEG images which do not contain any transparencies by default.

As such it is probably a good idea to tell IM to give all images an alpha channel using the "-alpha Set" operator before applying the 'dissolve' composite method.

The biggest caveat with using dissolve on both images is that the transparency effects the average. That is, dissolving two images by 50% will always result in the colors being semi-transparent, even when both input images are fully opaque. For example:

  convert dragon_sm.gif star.gif -alpha on \
          -compose dissolve -set "option:compose:args" 50,50 \
          -gravity South  -composite     dissolve_50_50.png
  composite -compose Dst_Over -tile pattern:checkerboard \
            dissolve_50_50.png   dissolve_50_50_bg.png
[IM Output]

You can see that after overlaying the image over a checkerboard pattern, that all parts of the image are at least semi-transparent. Though the actual parts overlaid is less transparent than any part where one of the source images is transparent.

The only time you will get a fully-opaque image from a 'Dissolve' composition is if one of the images (usually the 'background') is not dissolved (a 100 percent value), and remains opaque. This is why the default is to use a 100 value for the 'background' , at least at first.

The following are special cases for specific "-dissolve" arguments...
0x0 Both images are dissolved to full transparency.
Equivalent to a 'Clear' compose method.
0 Just the background image unchanged (source made transparent).
Equivalent to a 'Dst' compose method.
100 A normal overlay of the overlay image onto the background.
Equivalent to a 'Over' compose method.
200 The overlay image on a blank canvas (background made transparent).
Equivalent to a 'Src' compose method.

The "-dissolve" compositing method is commonly used as an alternative way of Watermarking with Images, particularly with color watermarks.


Blend Two Images Together

The "-blend" compositing method provides what the "-dissolve" compositing method was originally intended to provide, before it was hijacked for other more basic operations.

Where as the "-dissolve" method overlays images on top of each other, "-blend" merges images together such that both images are treated equally (being just added together), according to the percentage arguments given. As such you can achieve the same result (except in final image size) by swapping the percentages and the image arguments. This is not the case with "-dissolve" method.

In otherwords, "-blend" is associative (arguments are swappable), while "-dissolve" is not.


    composite -blend {percent} overlay  bgnd  result


composite -blend {src_percent}x{dst_percent} overlay bgnd result

convert bgnd overlay -compose blend \
    -set "option:compose:args" {src_percent},{dst_percent} \
    -composite result
If only a single percentage value is given, it is used as the dissolve percentage for the overlay, while the background image is dissolved by the exact opposite amount. That is a "-blend 30" will dissolve the overlay by 30%, and the background by 70% before the two images are added together. thus it is equivalent to "-blend 30x70". The result of this is that the opacity of the two images (in the areas overlaid) will still add up to 100%.

By giving two percentages you can control exactly how much of the two images are to be merged together.

Here is a table of results with various dissolve arguments...

  composite -blend {argument}  -gravity South \
            compose_R.png compose_plus_GB.png  -matte  {result}
[IM Output] [IM Output]
[IM Output]

From the results you can see that "-blend" will let you slowly replace one image with another equally without overlay.

If you overlay the result of a blend on a black canvas, say the size of your display, you can easily make a respectable slide show program in which one image slowly dissolves into another.

You can also see that because the images are added together (internally it uses the 'Plus' compose operator), you can easily overload the color channel maximums, producing some artifacts. A 100% white color in particular will ensure nothing of the other image will be visible as all colors channels are already at their maximum.

It is recommended that in most situations you only need to use the single argument version of blend.

As with "-dissolve", the background image must contain an alpha channel for "-blend" to work correctly, to dissolve the background image.

As such it is probably a good idea to tell IM to give all image arguments an alpha or transparency channel using the "-matte" operator, before the "-blend" is applied to overlay the images.

The following are special cases for specific "-blend" arguments...
0x0 Both images are dissolved to full transparency.
Equivalent to a 'Clear' compose method.
0 Just the background image unchanged.
Equivalent to a 'Dst' compose method.
100 The overlay image on a blank canvas.
Equivalent to a 'Src' compose method.
100x100 Just the two images added together.
Equivalent to a 'Plus' compose method.
50 Average of both images. This is equivalent to the "-average" image sequence operator, but with two images. (See also Averaging Images)

Blend verse Dissolve

While both Dissolve and Blend will make images semi-transparent "-dissolve" composes the image using 'Over', while "-blend" merges the images using 'Plus'.

This may not seem like much, but it can be very important, as it definines how the two composition methods handle parts of the image which are not overlaid, or in areas where the overlay is transparent.

For example.

  convert dragon_sm.gif star.gif -alpha on \
          -compose dissolve  -set "option:compose:args" 50 \
          -gravity South  -composite     dissolve_50.png
  convert dragon_sm.gif star.gif -alpha on \
          -compose blend  -set "option:compose:args" 50 \
          -gravity South  -composite     blend_50.png
[IM Output]
Dissolve
[IM Output]
Blend

However the default handling of the second '{dst_percent}' argument is designed so the two methods will produce the same result when you compose two images that are both fully-opaque, and completely overlay each other, with the same single argument value between 0 and 100.

For example, here I merge the 'dragon' image with the built in 'rose' image. I crop both images to the same size, so that both fully-opaque images can fully cover each other.

  convert dragon_sm.gif rose: -crop 70x46+0+0 +repage -alpha on \
          -compose dissolve  -set "option:compose:args" 50 \
          -gravity South  -composite     dissolve_50_opaque.png
  convert dragon_sm.gif rose: -crop 70x46+0+0 +repage -alpha on \
          -compose blend  -set "option:compose:args" 50 \
          -gravity South  -composite     blend_50_opaque.png
[IM Output]
Dissolve
[IM Output]
Blend

If you were to compare these two images, you will find they are exactly the same.

Using Blend to Modify a Single Image

Blend is basically an 'interpolation function', or 'weighted average' allowing you to combine two opaque images in a controlled linear way. That is 30% of the source plus 70% of the background, to produce a new 100% opaque image.

It can however do more than just combine two images. It can also be used to brighten, set contrast, saturation, colorize and even sharpen a specific image.

This use of blend is discussed further in a document found by BugBear <bugbear@papermule.co.uk> on the WWW, Image Processing by Interpolation and Extrapolation a copy of the one on Grafica Obscura (the page is not directly linkable from external source). This document is recommended for further reading on using this function.

Extrapolation ability was added to the "-blend" operator in IM v6.3.5-10.

For example, here we can make the rose image brighter or darker by blending it with a pure black image of the same size.

  composite  -blend   0  rose: -size 70x46 xc:black -matte blend_dark_0.jpg
  composite  -blend  50  rose: -size 70x46 xc:black -matte blend_dark_50.jpg
  composite  -blend 100  rose: -size 70x46 xc:black -matte blend_dark_100.jpg
  composite  -blend 150  rose: -size 70x46 xc:black -matte blend_dark_150.jpg
  composite  -blend 200  rose: -size 70x46 xc:black -matte blend_dark_200.jpg
[IM Output]
0%
[IM Output]
50%
[IM Output]
100%
[IM Output]
150%
[IM Output]
200%

As in any of these extrapolated blend examples, 0% is the 'destination' image the "-blend" operation is applied against while 100% is the original 'source' image unchanged.

Similarly blending with a pure gray image lets you adjust any images contrast.

  composite -blend   0 rose: -size 70x46 xc:'#808080' -matte blend_gray_0.jpg
  composite -blend  50 rose: -size 70x46 xc:'#808080' -matte blend_gray_50.jpg
  composite -blend  80 rose: -size 70x46 xc:'#808080' -matte blend_gray_80.jpg
  composite -blend 100 rose: -size 70x46 xc:'#808080' -matte blend_gray_100.jpg
  composite -blend 120 rose: -size 70x46 xc:'#808080' -matte blend_gray_120.jpg
  composite -blend 150 rose: -size 70x46 xc:'#808080' -matte blend_gray_150.jpg
[IM Output]
0%
[IM Output]
50%
[IM Output]
80%
[IM Output]
100%
[IM Output]
120%
[IM Output]
150%

Here I blend the rose image against its blurred version producing an 'unsharp' operation (sharpening an image by extrapolating from its blurred form).

  convert rose: -blur 0x5  rose_blurred.png
  composite  -blend   0  rose: rose_blurred.png -matte blend_blur_0.jpg
  composite  -blend  50  rose: rose_blurred.png -matte blend_blur_50.jpg
  composite  -blend 100  rose: rose_blurred.png -matte blend_blur_100.jpg
  composite  -blend 150  rose: rose_blurred.png -matte blend_blur_150.jpg
  composite  -blend 200  rose: rose_blurred.png -matte blend_blur_200.jpg
[IM Output]
0%
[IM Output]
50%
[IM Output]
100%
[IM Output]
150%
[IM Output]
200%


Watermark Option - Compose 'Modulate'

The "-watermark" composite option or the "modulate" compose method, is meant to dis-color images in HSB space for copyright purposes.


    composite -watermark {brightness}[x{saturation}] overlay  bgnd  result


convert bgnd overlay -compose modulate \
    -set "option:compose:args" {brigthness}[x{saturation}] \
    -composite result
The 'overlay' image is an alpha masked black and white image, which is used to brighten/darken the destination image by the 'brightness' percentage given. A 'brightness' of '0' makes no change in the image brightness, whole a value of '100' replaces the brightness with the intensity of the overlay image. That is, if the overlay is black the destination is made black, if white the destination image's color will be fully saturated.

The 'saturation' defaults to '100' producing maximum color saturation. If set to '0' the masked area will be de-saturated to black and white.

Here is a table of results with various arguments...

  composite -watermark {argument}  -gravity South \
            sphinx.gif  cyclops.gif   {result}
[IM Output] [IM Output]
[IM Output]
A good value for lightly watermarking images is a brightness of about about 15 to 30 percent.

The following are special cases for specific "-watermark" arguments...
0 No change is made to the destination image at all.
100 Destination made black where overlay is black, and fully-saturated color hue where overlay is white
0x0 The masked overlay area is de-saturated to gray-scale
100x0 The gray-scale overlay is simply overlaid 'ATop' of the destination.

For other watermarking techniques see, Watermarking with Images.

Using a Compose Mask to Limit the Composed Area

The "composite" command and "-composite" operator will also take a third masking image which will limit the area effected by the "-compose" method.

For example given two images, and a mask image you can overlay part of the source image onto the background image, as defined by that mask. Please note however that the background image still defines the final size of the resulting image.

  composite tile_water.jpg   tile_aqua.jpg  moon_mask.gif   mask_over.jpg
[IM Output] [IM Output] [IM Output] => [IM Output]

The mask image is considered to be part of the destination image, defining what parts of the destination can be modified by the result of the alpha composition. That is, the white parts can be modified, while black parts (and parts outside the mask image) are left as is.

Unfortunately while "-gravity" and "-geometry" settings will let you re-position the source image, the mask image is NOT re-positioned, and remains aligned with the destination image.

So lets just be clear about this...
The mask is aligned to the original background image.
Any gravity/geometry setting is not applied to it.

That means that if I want to re-position the mask, I need to enlarge the mask image with the appropriate amount of black rows and columns. See Splice, adding rows and columns of pixels. For example here is a "convert" version (source and background image arguments are swapped), with the mask image adjusted so as to move it relative to the background image.

  convert tile_aqua.jpg   tile_water.jpg \
          \( -background black -splice 10x25+0+0 moon_mask.gif \) \
          -composite   mask_offset.jpg
[IM Output]

Remember that the the "convert" commands "-composite" operator specifies the destination or background image first.

The result is like giving the mask an offset of '+10+25' but with neither the source or background images moving.

If you want to align the mask with the source image you may be better off masking the source image separately (using 'Copy_Opacity' or some other technique). Then you can position that result onto the background without alignment problems.

Here is a similar example, but this time I use a gradient mask the same size as the background image so as to blend the two images together, producing a 'shallows' effect.

  convert tile_aqua.jpg  tile_water.jpg  -size 94x94  gradient: \
          +matte  -composite   water_shallows.jpg
[IM Output]

This provides a simple way of overlapping two images. See Overlapping Photos.

Compose Mask and Transparency

You may think from the above that using a three image composite mask is very much like using the 'Copy_Opacity' to set a transparency of the overlay image, then composite that over your background. And for images without any transparency (such as the above) you would be right. But that is not the whole story.

First the mask is tied into the destination image, rather than the source image, so it is not offset or gravity effected.

Also unlike 'Copy_Opacity' the mask image is treated as purely a gray-scale image. IM will ignore any and all alpha or matte transparency the mask may have. As such you do not need to worry about the use of a "+matte" operator to junk any alpha/matte channel in the mask image.

And finally the mask works by limiting the area which was modified, which is very different to just masking the source image.

For a simple 'Over' composition, this is the same as if the mask is multiplied with any transparency in the source image, to limit what is overlaid. As such for completely opaque source images you can think of it as the transparency for the source image.

For example, overlay two circles as normal then overlay them with a mask limiting the area in which the destination image is changed.

  convert -size 60x60 xc:none -fill red  -draw 'circle 35,21 35,3'  m_src.png
  convert -size 60x60 xc:none -fill blue -draw 'circle 21,39 24,57' m_bgnd.png
  convert -size 60x60 xc:   -draw 'polygon 0,59 59,0, 0,0'          m_mask.png

  composite m_src.png  m_bgnd.png                   m_over.png
  composite m_src.png  m_bgnd.png   m_mask.png      m_over_masked.png
[IM Output] [IM Output] => [IM Output]
[IM Output] [IM Output] [IM Output] => [IM Output]
The result is equivalent to the red circles image being 'masked' by the given gray scale mask, which is then overlaid onto the destination image.

However with any other type of alpha composition method, you are better of just thinking of the mask as limiting the area of effect, rather than as a transparency mask of the source image.

Here I used a 'Src' method to replace the masked area in the destination with the contents of the source image.

  composite  m_src.png  m_bgnd.png  m_mask.png  -compose Src  m_src_masked.png
[IM Output]

As you can see only the area with the defined mask is actually replaced by the result of the alpha composition. If the mask was only used to modify the transparency of the source image the above would only show the source image and nothing from the background image.

FUTURE:  Using masked composition to overlay an object in front of a
backdrop, but behind some foreground object.  Also develop a animated example,
of something being obscured by foreground objects in the destination. 
The above was a major long term bug involving composite masking when you involved source or overlay images with transparency, and or attempted to use other alpha compositions other than the 'Over' compose method. See Composite Mask Bug for details.


Compose using Image Tiles

The "-tile" setting in "composite" is very different to that same setting in either "convert" or "montage". If given it means that the source image is to be tiled over the background image.

For example here we tile a 'color star' over a netscape color map image...

  composite  -tile star.gif   netscape:   tile.gif
[IM Output]

One common use of composite tiling is to tile a semi-transparent copyright or some other notice over images before publishing them on the net. For examples of this see the last examples of Watermarking with Text.

Note that the setting is essentially (at least at this time) argument-less. It is only a Boolean on and off flag to the final "composite" operation. Consequently you can not use it to tile a background image as that would mean IM can not use the background image to set the final size of the result.

However you can tile an image under another image using 'Dst_Over' instead.

  convert -background none -pointsize 36 label:'Tile Under'  png:- |\
  composite -tile bg.gif  -   -compose Dst_Over   tile_under.gif
[IM Output]

Also many of the mathematical operators are associative, meaning the source and destination can be swapped without affecting the result (except the final image size).

Currently there is no simple method of doing a tiled alpha composition in the "convert" command. This is a shame as it would make Tiling with an Image already In Memory a lot easier than it currently is.


Special Composition Methods

There are also a few special purpose composition methods that have been added for one reason or another.

Mathematics (User Defined Mathematical Compose Method)

This composite method takes 4 numerical values to allow the user to define many different Mathematical Compose Methods.

The four arguments, "A", "B", "C", and "D", define the formula...
A*Sc*Dc + B*Sc + C*Dc + D
where "Sc" is the source or overlay image, and "Dc" is the background or destination image. All four values must be provided.

For example, we could generate the equivelent of a 'Multiply' compose method using the values "1,0,0,0".

  convert gradient_dst.png gradient_src.png \
          -compose Mathematics -set option:compose:args 1,0,0,0 -composite \
          mathematics_multiply.png
[IM Output]
Source
 + [IM Output]
Dest
=> [IM Output]
Result

Similarly by looking up or figuring out the formula needed you can generate other composition methods, such as...

Screen: 1-(1-Sc)*(1-Dc) => -Sc*Dc + Sc + Dc => -1,1,1,0

  convert gradient_dst.png gradient_src.png \
          -compose Mathematics -set option:compose:args -1,1,1,0 -composite \
          mathematics_screen.png
[IM Output]

Or 'LinearLight' which is directly defined using the arguments "0,2,1,-1"...

  convert gradient_dst.png gradient_src.png \
          -compose Mathematics -set option:compose:args 0,2,1,-1 -composite \
          mathematics_linearlight.png
[IM Output]

Similarly you can generate other compose methods such as...
 Compose Method   Mathematics Args 
Multiply 1,0,0,0
Screen -1,1,1,0
Exclusion 0,1,1,-1
Linear_Dodge 0,1,1,0
Linear_Burn 0,1,1,-1
Linear_Light 0,2,1,-1

Most other mathematical compose methods require either squares, square-roots, division, or even multiple special piece-wise functions and conditionals, which prevents them from being defined using a simple smooth polynomial function that this method provides.

Other interesting compose methods you can create include an expanded alternative to LinearLight...

  convert gradient_dst.png gradient_src.png \
          -compose Mathematics -set option:compose:args 0,1,1,-0.5 \
          -composite  mathematics_linearlight_2.png
[IM Output]

This particular DIY composition is important as a means of doing Adding Biased Gradients such as sine waves.

Or even...

  convert gradient_dst.png gradient_src.png \
          -compose Mathematics -set option:compose:args 0,1,.5,-.25 \
          -composite mathematics_linearlight_3.png
[IM Output]

More importantally this composition method can be used to do special types of Mathematics on Gradients that would otherwise be very complex to achieve using multiple individual steps.

The 'Mathematics' compose method was added to IM version 6.5.4-3. And is currently only available from the "compose" command. It is not available from the "composite" command due to its need for arguments.

Change_Mask (Make similar pixels transparent)

This is an unusual method that will only make specific pixels in the destination image full-transparent. That is, the pixels in the destination image that match the given source image, according to the current Fuzz Factor setting.

This can be used for example to re-add transparency to an image that was overlaid onto a complex (but very different) background. For example, this was exactly the problem presented by Jesper Eije...

  convert bgnd_overlaid.gif   bgnd.gif  \
          -compose ChangeMask  -composite  bgnd_removed.png
[IM Output] [IM Output] => [IM Output]

Easy.

Note that as JPEG image colors often have slight color changes due to the lossy nature of the file format, a small Fuzz Factor setting will be needed to match very similar colors

Also if the changed part of the image happens to match the background color or pattern, you will get 'holes' in the resulting image or mask, as such caution is always advised when using this with images that are very similar.

By swapping the two images, so the background image is given as the destination image, you can extract the parts of the background that was replaced or modified by the overlaid image.

  convert bgnd.gif  bgnd_overlaid.gif \
          -compose ChangeMask  -composite  bgnd_replaced.png
[IM Output]

Note that the result is only a transparent shape mask of the original background image where similar pixels are just cleared to transparency. It will make no attempt to generate partial transparencies, or change colors, and as such could leave a 'halo' of slightly different background colors around the image where the original overlay and the background color merged together.

As this composition method only 'clears' pixels to full-transparency, a matte channel is always added to the resulting image. The color of the destination image is not however cleared as it is in most other Alpha Composition methods. As such you can negate the alpha channel, to get the unchanged colors.

  convert bgnd_overlaid.gif   bgnd.gif -compose ChangeMask  -composite \
          -channel A -negate      bgnd_unchanged.png
[IM Output]

In this case the order of the input images does not matter, unless a large Fuzz Factor was set. Remember the colors will come from the destination image, with the difference between the images defining the resulting shape mask.

For more information on these problems see Re-adding Transparency to an Image.

The result is often limited in its direct usefulness. It can however be used to generate bitmap masks of the changes between the images (hence its name).

The 'ChangeMask' composition method was added to IM v6.3.4, to provide a method for Optimizing Transparency for GIF Animations. No other existing composition method provided the needed requirements, without combining 3 or more composition methods. Specifically the Boolean (or fuzz factor thresholding) requirement needed for transparency optimization.

The result however is so useful in its own right that it was made available for direct use by users, and so defined the name of this rather complex composition method.

Image Mapping Effect Methods

There are also a couple of special methods that are not strictly composition methods. Rather than directly combining the two images on a pixel by pixel bases, the source or overlap image is a special control map, for some larger effect.

While the methods they represent are relatively simple their use is so complex they have their own example section. Image Mapping Effects.

These special methods include...

The 'Blur' method provides a method of bluring images in different ways on a pixel by pixel bases. It can generate a wide range of DIY image blurring effects. See Variable Blur Mapping for details.

The 'Displace' method on the other hand provides both an absolute and relative pixel lookup displacement technique that generates not only specific image distortion methods, but also glass, lens, and ripple, effects. See Distort and Displacement Mapping for details.


Created: 5 January 2004
Updated: 24 March 2010
Author: Anthony Thyssen, <A.Thyssen@griffith.edu.au>
Examples Generated with: [version image]
URL: http://www.imagemagick.org/Usage/compose/