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
OverDst OverSrcCopyReplace
DstInDst InOutDst Out
ATopDst ATopClearXor
Mathematical Compose Methods
MultiplyScreenBumpmapDivide
PlusPlus BlendingAddMinusSubtract
DifferenceExclusion LightenDarken
Shading Composition Methods (Light, Dodge, Burn)
OverlayHard LightSoft Light,   Pegtop Light,   Pin Light, Linear Light, Vivid Light,
Linear DodgeLinear BurnColor DodgeColor Burn
Channel Copying Methods
Copy Opacity,   Copy RedCopy GreenCopy Blue
Copy CyanCopy MagentaCopy YellowCopy Black
HueSaturateLuminizeColorize
Special Composition Methods
MathematicsChange Mask
Dissolve one Image Over Another
Blend two images together
Watermark or Modulate Image
Variable Blur Mapping
Using a Mask to Limit Composed Area
Composite using Image Tiles

Image Composition is the technique of combining images, (with or without transparency, or alpha channels) together in some way. This is generally performed either using the "composite" IM command, where it is the main job. But it is also often done either as part of a larger sequence of operations, or internally as a part other image operators.


Image Composition in IM

Image Composition is the process of merging two (and only two) images together in various ways. It often refers to 'Alpha Composition' which describes what the results should be depending on what parts of the overlay is transparent or not. But it is also used for blending and averaging images, transfering image channels, cutting out, joining, or layering odd shaped segments of images, or as part of complex mathematical operations.

A good alternative introduction on Image Composition is SVG Compositing in 30 Minutes. Or you can find out the exact mathematical details by looking at the SVG Alpha Compositing page, which also defines the most important image composition methods.

The follow 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 traditional and normal method of compositing in IM, in which that is it primary, and pretty well only task that that command does. This shows just how important image composition is.

The "convert" operator "-composite", however also can do image composition, generally as part of a large image processing task. Note the reversal of the order of the images when using "convert". This ordering is for practical reasons, as you generally are working with a primary canvas, over which you then want to prepare and merge into a new images. The order of the images is important, as you will see.

Examples of both techniques (and more) can be seen in given in Layers of Multiple Images, and this is recomended reading before proceeding further.

Defination and Terms

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

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


Sometimes on rare occasions a third 'mask' image is added to the above. This image is usually 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 destination 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 exactly what the various composition 'methods' do, and how you can make use of them for various purposes.

A basic table of the results of the compose methods, see Tables of Compose Methods. Note that these tables don't really show the methods 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 actually short for the more verbose compose method names: 'Src_Over', 'Src_ATop', 'Src_In' and 'Src_Out'.

On top of the huge list of "-compose" methods, there are some that also 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" can now also pass special arguments to the "-composite" operator, by using the special "-set" option "option:compose:args". For examples of this see the special Dissolve and Blend, methods below.

Image Composition Operators

Apart from the 'direct' two image compositing styles already shown above, there are a number of other image operations that also use alpha compositing as part of their internal image processing.

Because of this these operators are effected by the current "-compose" setting, though they will either use their own internal positioning, or use a Layered Image virtual canvas offset positioning technique.

These compose effected operators include...
Layering Operators
These overlay a whole sequence of 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. Layering operators include "flatten", "mosaic", and the new "-layers merge".

Edge Expansion Operators
Operators which overlays each individual image on individual canvases. This includes operators such as "-border", "-frame", and "-extent". (See Adding/Removing Image Edges).
The "montage" program
The "-frame" montage setting makes use of the previous image framing operator, to frame the list of images before positioning them on the background canvas. More specifics can be found in Montage Background and Transparency.

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

It is the only image composition technique available to "mogrify" as it gets the 'overlay' image from an external source, allow it to overcome that commands no-list-operator limitation.

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 allows you compose 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" effected "-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. As such I refer you to there.

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

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

Layer Canvas/Page Offsets

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

To handle any number of multiple images, new background image is generated, using the current "-background" color, and with a size that is dependant on the operation being performs. This is then taken as being the 'destination' image (canvas) and ALL given the images are composited onto this new canvas one at a time in sequence.

As such even if only two images are given, a new image is still created, and two separate compositions are applied. That is it can be slower. However all the images are treated 'source' images, only the order they are given determines the result.

The 'layer' offset however is NOT gravity effected, But as each individual image can have a separate 'canvas offset', it is much better suited for the composition of multiple images 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.


Note that only one composition technqiue allows you to use BOTH positioning methods simultaniously, the multi-image sequence Layers Composition operator. 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 '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. Remeber however that the image order is reversed when using "convert"s, "-composite" operator.

Note that these 12 methods define not only which of the two images are 'visible' in the result, but also how it effects the parts 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 '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 setting can be used 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.

The final thing that you shoul notice about the Duff-Porter Alpha Composition methods, is that at no time do they make 'transparent colors' visible. This is important as a transparent part of the image has a undefined color, which could have ANY color. See Controling Image Transparency, for more details about 'transparent colors'.

This is why Duff-Porter composition is often the prefered masking method, unlike 'CopyOpacity' whcih simply completely replaces the Alpha Channel of an image, and thus 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 a '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.

For example here we overlaid the image using the "convert -composite" operator this time, but half way off the background. Note the reversal of the image order for the "convert" form of alpha composition.

  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 almost exactly 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. As such the output image size will set by the now foregrounded '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 overlays position relative to the background can be modified, and is clipped by the background. This is what makes this operator such a important and useful operator to know.

The "-tile" setting of "composite" also makes this form of 'over' very useful as a way to tile underneath a image. For example lets 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 just completely replaces the background image with the overlay image. The colors and transparency in the background is completely junked, leaving a blank image the same size as the original destination, over which to apply 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.

The other aspect of this is that the size of the final image does not change even though the image content itself has. 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 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 really 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'. But also the original images 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 simply)

This operator is not strictly part of the 12 'Duff-Porter' compose methods, (which is why it was not on the chart above), but 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 out a small section of a large 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 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 their is no transparency, it would then be exactly like 'Over'.

How it actually works is that is that internally it uses a special composition control setting that tells IM, to not modify the parts that are not overlayed.

As of IM v6.5.3-4 this control setting can be set by the user, and is known as "compose:outside-overlay" and you turn it off by setting it 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 basically does absolutely nothing. The source, or overlay image is completely ignored, and the destination or background image is left completely unchanged.

The methods real use, is as a means of 'turning off' a alpha composition operation, in other image operators.

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

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

The "-matte" operator in this command is needed to ensure an Alpha Channel is available, or you will end up with a black middle, rather than a transparent one. The "-bordercolor" in turn defines the color inside of 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 cut out the overlay images shape from the background image, like a cookie cutter which cuts out a cookie shapes from cookie dough.

For example lets 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 'Copy_Opacity' method, you can NOT use a greyscale image as the mask, as only the overlay images 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' analogy 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 can add paint, but he can't remove paint, by painting over it.

By drawing the shape you what to erase onto a transparent canvas, you can then use 'Dst_Out' to then 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, as the case may be.

For example suppose you wanted to draw a crescent moon symbol on a transparent canvas. This alpha composition method makes this difficult shape, easy to draw, by just 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 parenthesis, 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 a 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 while want to add a highlight on it as if it is a 3 dimension ball. Well we can create the circle, and the highlight then overlay the highlight using 'ATop' to limit it the the circle itself.

  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 to 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 a "-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 continue this to 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, but 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) ensures the background has a matte/alpha channel to it to clear the destination image to.

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 of 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. What it does is to overlay the two images together, but then clear the area that overlapped back 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 xored on the above results.

  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 and odd number of overlay will result in the last image overlaid showing though.

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


Mathematical Compose Methods

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

The first thing to note is that they are rarely used with images involving transparency. But if they are applied to such images almost all of them produce an 'Over' blending. That is the areas of overlap will have the mathematical operation applied to them, while any non-overlaped areas will be a copy of the source or background image, as appropriate.

This not only applied to all mathematical operators, but also to Shading Operators (new section) which are simply fancier forms of mathematical operators.

If you like to know more about the mathematical formulas for these compose methods see the definations in SVG composition guide (2009), also in Pegtop Blend Modes and SimpelFilter Photoshop Blend Modes.

The special gradient image you can see to the right of each of the following operators, defines the operator in terms of how it effects the color values. It is produced by composing two gradient images, in something very simular to the following...

  composite gradient_src.png -compose Multiply gradient_dst.png \
            gradient_result.png
[IM Output]
Source
 + [IM Output]
Dest
==> [IM Output]
Result

Basically if you user 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. Each channel value (Red, Green, Blue), in whatever ColorSpace the images are in, will be applied completely separatally to each other.

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

[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 this will only darken images, it will never brighten it. That is it 'attenuates' an image toward black, which makes this compose method a 'Burn' style of composition.


  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 is basically basically black (or greyscale) lines on a mostly white background, such as text images. If both images contains 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 needed to add some diagrams to a page of text which was to be included into a ray-traced image. You can see this page, in the image results on 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 Masking.

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 a Evaluate PowerOf operation with a value of "2.0".

This is used for example for 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.

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 is 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 it will only make an image brighter, never darker. This is a style of composition known as 'Dodge' composition.

The composition method perfect for overlaying white text on black backgrounds 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 and example of using this to overlay a white shape on an image.

[IM Output]

Bumpmap (greyscale multiply)

The 'Bumpmap' method is essentially exactly 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 sort of '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)

Basically the destination image is divided from the source image. However as color values are thought of as 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 swaped. so that the divisor image much be given before the numerator!

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 here I have a image of some hand written text which was very roughly scanned (using a digital camera without flash, then reduced in size to remove digital noise). The paper had 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.

As you can see it is a lot clearer that 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 was wanted.

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

Using smaller blurs can produce an alturnative 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 in some cases. See 'Color_Dodge' for examples of equivalent command.

[IM Output]

Plus (Add colors together to form a blend)

Basically adds 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 channle 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-alias inconsistencies. The better way is to use the 'Screen' compose method. This uses a multiplication rather than a additive method of increasing brightness.

Plus - Special blending Operator

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

This is important as it allows the joining non-overlaping masked images together. for example see the merging of Dst In and Out images.

It also allow 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 posible.

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'

[IM Output]

Add (Modulo-Plus)

The 'Add' composition is exactly the same as 'Plus' except that when the resulting color goes beyond white, it is wrapped around (modulus) back to black.

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

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

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

  composite gradient.png \( gradient.png -rotate -90 \) \
            -compose Add   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 Add -flatten  gradient_venetian.png
[IM Output]

Which produced a gradient which was repeated 5 times. Note how I used a background of 'gray50' to effectively 'roll' the gradient half a modulus cycle forward.

[IM Output]

Minus

This is an mathematical oddity in the math compose methods, The result is an image in which one image is subtracted from the other. Its formula is:   Src - Dest

However the opaqueness of the pixels are also subtracted (if present), as such you will not see the result unless you also turn off the images matte channel.

For example lets subtract one 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]

Note that while the above result looks the similar to a 'Out' or a 'Dst_Out' method, in that it will 'erase' parts of an image, the colors are also effected. As such do not use it to erase parts of images.

We can see that colors were also effected, removing the red circle completely from the source image, if we make all the pixels full-opaque. That is this is a color and alpha channel subtraction.

  composite -compose minus  compose_plus_RGB.png  compose_R.png \
            +matte compose_minus2.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.

Howvever this will use the more normal 'Over' alpha blending of the transparent pixels, making it more useful for image mathematics.

This is how 'Photoshop' implements 'Minus'

[IM Output]

Subtract (Modulo-Minus)

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

As side effect of this subtracting the transparency channel will also have wierd effects, resulting in different parts of the image being made transparent and opaque in a seeming uncontroled way.

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

As with all mathematical operators it is probably best to handle transparency separatally to the color channels, with some care so that you get the results you are actually expecting.

[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 difference between the colors '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 comparator.

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 fact, the compose 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, was a way to merge multiple difference images together. That way that the final image shows the changes of all the images, not just between two images. That is given images A, B, C, then use difference 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 related to how Xor composition blending operator handles the alpha transparency values in images.

[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 darken 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 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.

FUTURE: create a 'intensity' version of 'Lighten' and 'Darken'


Shading Composition Methods -- Light, Dodge, Burn

These methods modify the colors of image in highly complex ways, and are typically used to adjust the shade or intensity of the image, to make some areas brighter and others darker, in various ways. Because of this when using one of the images is usally a grayscale overlay of some sort.

These fall into three sub-catagories of related operators.
'Burn', which generally only 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 the at least 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 appropriatally. Which image should be the color, and which gray-scale, is unfortunatally debatable and depends on how the method was implemented. There is no standard in this regard.

As a consequence of this many users do not understand or mis-use the operators, and even a guide on correct usage 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 was 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

However just swapping images like this is actually what the 'Hard_Light' composition method (see below), does. The only difference between them is which image is used for the destination image, and thus which image contains the size and extra image meta-data.

This tinting or adding color to mid-tine greys, 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. 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  circle_shaded.jpg
  composite circle_blue.jpg  circle_shaded.jpg \
            -compose Overlay    circle_shaded_tinted.jpg
[IM Output]  + [IM Output] ==> [IM Output]

For an more practical example of using the 'Overlay' method in this way, 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 Better 3-D Logo Generation example.

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 IM users had little understanding of this operator. Hopefully this will now change.

[IM Output]

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

This is exactly the same as 'Overlay' except the source and destination images are swapped.

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

So while 'Overlay' can be thought to added color to a gray-scale shaded object, 'Hard_Light' can be thought of as adding highlights to a colored image. The result is basically the same, just with the source and destination images swapped.

A typical use of this composition method is to add 'texture' to an existing image.

For example, here I adjust the colors of the "rose:" built-in using a "granite:" texture (after centering its histogram and muting its effects)...

  convert rose: \
          \( granite: -blur 0x.5 -normalize -fill gray50 -colorize 70% \) \
          -compose hardlight -composite compose_hardlight.jpg
[IM Output]

Note that overlaying pure black or pure white will result in the destination image being pure black or white, in those areas. As such you may like to remove the contrast of a overlaid texture (such as the use of "-colorize" in the above) to mute the effects of such extreme colors.

Of course if you want to add both extreme highlights (like a reflected light) or dark shadow effects to an existing image, using the one operation, thea this operator is ideal for your purposes.

For another better example of this see Overlying a Texture in the Photo Cookbook.

[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 is modified so as to produce a softer contrast to the colors.

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

For example here is the a '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 image.

Here I show the color change limits achieved as a result of using pure black, white and gray color overlays.

  convert -size 46x70 gradient: -rotate 90 \
          -ordered-dither threshold,3   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.

Unfortunatally it was the specification not the implementation truned out incorrect, a fact that was only fixed in the March 2009 SVG specification. As such for IM v6.5.4-3 and later this operator now work 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 seperate functions joined together. The 'Pegtop_Light' method produces a near identical result as 'Soft_Light', but uses single smooth function, without any discontinuation, not even the minor, hard to see one used in 'Soft_Light'. because of this it is actually much simplier and faster.

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

For details see the Pegtop SoftLight Alternative page.

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)

This is another image shading method, but one that 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 subrtact 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 equivelent of 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 a sort of a 'Add Minus One' composition, to produce 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. That is
(1-Src) + Dest - 1 ==> Dest - Src

That is with no transparency, these two commands 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.

However it is different to the more direct IM 'Minus' coposition method, in that 'Linear Burn' will use a 'Over' alpha blending method for handling transparency. See Plus Blending for details.

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 a placing some object on top of an image for a very very long time.

A pure black overlay covers the background from all changes, while a pure white overlay will make all the background colors white, except the 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 alturnative 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".
[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 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".

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 images transparent parts. But this 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 for what this operator is used for, 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, lets 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 has transparent components that that you do 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 a "-matte" channel added.

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 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.


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 much 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

Simularly by looking up or figureing 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]

Simularly 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 form being simply defined using a simple smooth polynomal function this method provides.

Other interesting compose methods you can create include a expanded alturnative 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 actually 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.

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 matches 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 actually 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 makes 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.

Also 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.


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 of the dissolve of the background, so while one image dissolves in 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 a 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 image an alpha channel using the "-alpha Set" operator, before applying the 'dissolve' composite method is applied.

The biggest cavat with using dissolve on both images is that the transparency effects they 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 were at least partially 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 (usally the 'background') not dissolved (a 100 percent value), and thus remains opaque. This is why a 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 "-dissolve" method overlays images on top of each other, "-blend" method 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 very easily make a very 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 thus recommended that in most situations you would only need to use the single argument version of blend.

As with "-dissolve", the background image must contain a 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 only with two images. (See also Averaging Images)

Blend verse Dissolve

Now 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 handles part 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, actually 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 60x45+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 60x45+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 combine two opaque images together 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 combining two images, but 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 being 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 a '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 be used to purposefully 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 a alpha masked black and white image, which is used to brightens/darkens 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 brightnes 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 made a 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 bade 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.

Variable Blur Mapping

Added to ImageMagick version 6.5.4-0, the "-compose" method 'Blur' provides you with a method of replacing each individual pixel by a Elliptical Gaussian Average (a blur) of the neighbouring pixels, according to a gray-scale mapping.


    composite -blur {Xscale}[x{Yscale}[+{angle}]]  blur_map  image   result


convert image blur_map -compose blur \
    -set "option:compose:args" {Xscale}[x{Yscale}[+{angle}]] \
    -composite result
This means you can blur one part of an image, while leaving another part completely normal, or produce effects such as Tilt-Shift, where a real world image is made to appear more like a small artifical model.

For example, here I blur one half of a image of a koala while leaving the other half completely un-blurred...

  convert -size 37x75 xc:black -size 38x75 xc:white +append  blur_map_bool.gif
  convert koala.gif blur_map_bool.gif \
          -compose blur -set option:compose:args 5 -composite \
          blur_koala_bool.gif
[IM Output]  + [IM Output] ==> [IM Output]

As you can see any pixel that was 'white' on the 'blur_map' image was blurred by the amount given, while anything that was 'black' was not blurred. In other words a masked blur. Which could of course be done many ways.

The tricky part of the above is that only the areas blurred will take extra time needed. Pixels which are not blurred, do not need this extra processing. This makes the above much faster than either using a Masked Composite which is the same as bluring the whole image and merging the results. This time saving can be even more important when dealing with for large blurs of very areas of an image.

What makes this blur mapping more versitile is that it is varable. That is if the blur mapping for a pixel is a gray color, than you will get a corresponding smaller blurred result, using a smaller 'neighbourhood', for that pixel. Black in the blur mask is not blurred, while white is maximumally blurred, by the values given.

For example, lets make the koala more blurry toward his feet...

  convert -size 75x75 gradient:black-white blur_map_gradient.gif
  convert koala.gif blur_map_gradient.gif \
          -compose blur -set option:compose:args 5 -composite \
          blur_koala_gradient.gif
[IM Output]  + [IM Output] ==> [IM Output]

And here is the same blur again but showing how the blur varies with the height.

  convert blur_map_bool.gif blur_map_gradient.gif \
          -compose blur -set option:compose:args 30 -composite \
          blur_edge_gradient.gif
[IM Output]  + [IM Output] ==> [IM Output]

The 'Blur' compose setting uses a different technique to the normal Blur or Gaussian Blur Operators, as it is implemented by using a Gaussian Elliptical Area Resampling algorithm that was developed for scaled image resampling as part of Generalized Distortion Operator.

The elliptical area used for the neighbourhood resampling, also makes this method of blurring more versitile than a normal uniform 'circluar' blur provided by the operators "-blur" and "-gaussian-blur". The ellipse itself is defined by the 'width', 'height' of the sigma for the blurred area. The ellipse can also be rotated from a orthogonal alignment by the given 'angle' (clock-wise).

For example in the diagram we show how the blurred color of a single pixel will get its color from a rotated elliptical area, which is larger that the given 'sigma' width and height. The pixels in this area are then weighted and averaged according to a gaussian weighting function.
[IM Output]

As mentioned, this is exactly the same as what is used Generalized Distortion Operator to do a scaled lookup of the distorted pixels, especially in extreme distortions such as exampled in Viewing Distant Horizons.

As an example of the elliptical controls on the blur, lets a black dot using the same gradient blur map we used before. But this time we use long thin horizontal ellipse '30x0', rather than a circle. The 'x0' means no vertical blurring should be seen.


  convert -size 75x75 xc: -draw 'circle 36,36 36,5'  black_circle.gif
  convert black_circle.gif blur_map_gradient.gif \
          -compose blur -set option:compose:args 30x0 -composite \
          blur_horizontal.gif
[IM Output]  + [IM Output] ==> [IM Output]

As you can see the amount of the blur still varied with the map image provided, producing very little blur at the top of the image, and a lot of blur at the bottom. But also notice that the bottom edge is blurred horizontally equally in both directions.

Their is no vertical bluring to the image, The small amount of bluring at the bottom edge of the circle is caused by horizontal bluring, not vertical, though it may seem that way.

By either rotating the long thin ellipse using the third angle argument, or using directly defining a long thin vertical ellipse, you can blur the image vertically only...

  convert black_circle.gif blur_map_gradient.gif \
          -compose blur -set option:compose:args 0x30 -composite \
          blur_vertical.gif
[IM Output]

Note however that as the blur is not applied equally the top half appears less blurred than the bottom, because that is what we asked it to do. This in,turn distorts the image making it appear truncated.

Finally lets to this one more time but with a horizonatl ellipse rotated by a 45 degree angle.

  convert black_circle.gif blur_map_gradient.gif \
          -compose blur -set option:compose:args 30x0+45 -composite \
          blur_angle.gif
[IM Output]

The image may appear very odd, but that is because the variable blur map is vertical while the blur itself is angled, producing the odd looking effect, due to the mis-aligned angles of the ellipse and the blur map.

Note that using long thin ellipses like this is actually a lot faster that using a single large circle. In fact the "-blur" operator gets its speed by using two separate horizontal and vertical blurs, where as the "-gaussian" blur operator does a full 2 dimensional convolution in a simplar way to the 'Blur' composition method just described.

Note that it is the neighbourhood around each individual pixel that is used to generate the 'blurred color' for that pixel. That means that even though you may specify some part of an image to not be blurred, colors from that area may infact be used as part of the blur of neighbouring pixels.

Future example, attempt to blur a background, but not the foreground. This will fail!

For a practical example of Variable Mapped Blurs, have a look at Photo Tilt Shift Effect, and Distance Blurred Shadow Font.

Posible Future Addition:
At this time the angle of the ellipse cannot be varied across the image. You cannot for example blur an image 'radially' or 'rotationally' using this compose method (see Polar Cycle Tricks). This could be added sometime in future, all that is needed is to figure out an appropriate method method of enabling and inputting the angle map. Mail me if you have an idea.


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 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 is given first.

The result is like giving the mask a 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 creating a overlapped version of 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 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 basically 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 here I overlay are two circles as normal, then I 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 effecting 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.


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