ImageMagick Examples --
- ImageMagick Examples Preface and Index
- Converting Color to Gray-Scale
- Image Level Adjustments
- Negating Images (reversing black and white)
- Level Adjustment Operator (contrast and black/white adjustment)
- Reversed Level Adjustments (de-contrasting)
- Gamma Level Adjustment (mid-tone adjustments)
- Gamma Operator Adjustment (gamma without level adjustments)
- Level Adjustments by Color (adjust image levels using colors)
- Sigmoidal Non-linearity Contrast (non-linear contrast adjustment)
- Miscellaneous Contrast Adjustments
- Adjustments Using Histogram Modification (changing the histogram an image)
- Linear Histogram Stretching
- Normalize (auto-level stretching)
- Contrast Stretch (controlled stretching)
- Linear-Stretch (alternative stretching)
- Histogram Redistribution
- Equalize (uniform histogram redistribution)
- Gaussian Redistribution
- Histogram Redistribution Methodology
- DIY Level Adjustments (general tinting operators)
- Tinting Midtones of Images (general tinting operators)
- Uniform Color Tinting
- Midtone Color Tinting
- Sepia Tone Coloring
- Duotone Effect
- Color Tinting, DIY
- Color Tinting Overlay
- Global Color Modifiers
- Modulate Brightness, Saturation, and Hue
- Modulate the Hue Color Cycle
- Modulate DIY
- Modulate in Other Colorspaces
- Modulate in LCHuv and other Colorspaces
- Color Matrix Operator
- Solarize Coloring
- Recoloring Images with Lookup Tables
- Image Level Adjustments
generate_test", I use to create it.
|WARNING: The color processes below generally assumes the image is using a linear colorspace. Most images are however saved using a sRGB or Gamma corrected colorspace, as such to get things right colorspace correction should also applied first.|
Converting Color to Gray-ScaleGray scale images can be very useful for many uses, such as, furthering the processing of the original image or for use in background compositions. The best method of converting an image to gray-scale is to just ask IM to magick the image into a gray-scale Color Space representation for the image.
red' is quite a bright color compared to '
blue' which looks darker.
This is equivelent to the use of the '|
rec709luma' value is just one of many greyscaling formula that has been defined for use by the "
-intensity" setting (see below).
Here for example is the other common greyscaling formula
However there a many other methods, and meanings of 'gray-scale'...
For example, you can drain all the color out of the image by using the
Modulate Operator, to set all
color saturation levels to zero.
Lightness' value from that colorspace. However using a "
-define modulate:colorspace" you can specify other colorspace models to use. See Modulate in Other Colorspaces below. Note how the IM '
green' color I used for the center colored disk in my test image is not actually a pure green, such as used in the colored rainbow, but the half-bright green defined by the new SVG -- Scalable Vector Graphics standard. If you need a pure RGB green you can use the color '
lime' instead. See Color Name Conflicts for more detail.
Another way is to use the FX DIY operator to
average the three channels together to get a pure mathematical meaning of
The average of sRGB channel values also equivelent to the intensity channel
You can use the same adding channels technique to control the weighting of the
individual color channels. For example this is one DIY formula that you can
You can also use 'intensity' if you want the same meaning within the "|
However as the FX DIY operator is interpreted,
it can run very very slowly. For more complex operations you can use the
simpler Evaluate Operator, "|
A much more interesting technique is to extract a variety of different meanings of brightness by extracting the appropriate Color Channel from various Colorspace representations of the image. Examples see Grayscale Channels from Colorspace Representations.
Image Level AdjustmentsThe most basic form of adjustment you can make to images are known as 'level' adjustments. This basically means taking the individual RGB color values (or even the alpha channel values) and adjusting them so as to either stretch or compress those values. As only channel values are being adjusted, they are best demonstrated on a gray-scale image, rather than a color image. However if you adjust all the color channels of an image by the same amount you can use them with color images, for the purposes of either enhancing, or adjusting the image. Do not confuse this with the more automatic form of level adjustments, which we will look at in the next major section of examples below, Normalize Adjustments. This function will do exactly the same operation regardless of the actual content of the image. It does not matter if the image is bright, or dark, or has a blue, or yellow tint. The operations are blind to the actual image content. In demonstrating these operations I will be using a modified "
Image NegationThe simplest and most basic global level adjustment you can make is to negate the image, using the "
Direct Level AdjustmentsThe "
This method of de-contrasting an image however is very inaccurate and not recommended, unless you have an IM older than version 6.4.2 where you don't have access to the new Reversed Level Operator. You can use the "
Or by setting them to the same value, you can effectively call all the color values in the image to be thresholded. Using "
Note that unlike "
Reversed Level Adjustments -- Decontrasting ImagesAs of IM version 6.4.2 the Level Operator was expanded to provide a 'reversed' form "
Level Gamma AdjustmentsBoth the above "
Gamma Operation AdjustmentsThe "
One of the less obvious uses of "
Level Adjustment by ColorThe "
The plus form of the operator "
If you only specify a single color, without any 'comma' separator, that color will be used for both black and white points. That means all the colors in the image will be reset to that one color. (according to the current "
Sigmoidal Non-linearity ContrastFrom a PDF paper on 'Fundamentals of Image Processing' (page 44) they present an alternative to using a linear contrast control (level), with one using gamma correction known as 'sigmoidal non-linearity contrast control'. The result is a non-linear, smooth contrast change (a 'Sigmoidal Function' in mathematical terms) over the whole color range, preserving the white and black colors, much better for photo color adjustments. The exact formula from the paper is very complex, and even has a mistake, but essentially requires with two adjustment values. A threshold level for the contrast function to center on (typically centered at '
Miscellaneous Contrast Operators
-contrast and +contrast Rather useless minor contrast adjustment operator -threshold Threshold the image, any value less than or equal to the given value is set to 0 and anything greater is set to the maximum value. Note that like level, this is a channel operator, but if the default 'channel setting' is used only the gray-scale intensity of the image is thresholded producing a black and white image. magick rose: -threshold 45% x: You can force normal channel behaviour, where each channel is thresholded individually buy using "-channel All" magick rose: -channel All -threshold 45% x: -black-threshold -white-threshold This is like -threshold except that only one side of the threshold value is actually modified. For example, here anything that is darker than 30% is set to black. magick rose: -black-threshold 30% x: magick rose: -white-threshold 50% x: These operators however do not seem to be channel effected, so may only be suitable for gray-scale images!
Adjustments Using Histogram ModificationThis section was a joint effort by Fred Weinhaus and Anthony Thyssen. What is a histogram? A histogram is a special type of graph. It simply sorts the color levels of the pixels in an image into a fixed number of 'bins' each of which span some small range of values. As such each bin contains a count of the number of color levels (pixel values) in the image that fall into that range. The result is a representation of how the color values that make up an image are distributed, from black at the left, to white at at the right.
Histogram StretchingThe simplest techniques, like the previous example simply stretch the histogram of the image outward to improve the color range. However instead of just blindly picking the black-point and white-point for Level operation, they select points based on the images histogram. Basically they count up the number of color values in each histogram bin, from each of the two ends, inward until they reach some threshold. These points will then be used as the black-point and white-point for the histogram (level) stretching. Diagram needed Basically the histogram counts provide the graylevel values that the stretch will force to black and white. This means that all pixels in the image that fall within the range of bins from pure black to the selected black-point bin's corresponding graylevel will end up pure black. Likewise those pixels in the image that fall within the range of bins from from pure white to the white-point bin's corresponding graylevel will end up pure white. The pixels that are outside these points however will have been stretched outside the possible color range of values, and as a result they will be simply be set to the range limits. That is, these pixels are 'clipped' 'burned-in' as they are converted to the extreme of pure black or pure white color values. As a result if the 'threshold' limits for selecting the black-point and white-point is set too high, you will get lots of black and white areas in the image, with the resulting histogram having large counts (tall bars) at the extreme end bins. Example of severe burn-in -- Chinese Chess Image? Summary of 'stretch' operators... -contrast-stretch, and -linear-stretch all generate a histogram (using 1024 bins) to determine the color position to stretch. as such it is not 'exact'. The other difference is how 'zero' is handled, and that -linear-stretch actually does a -level operation to do the stretch, while -contrast-stretch uses histogram bin values for color replacement stretching (which introduces a 1024 quantum rounding effect. -normalize uses -contrast-stretch internally. A mathematically perfect normalization stretching operator is -auto-level. While a perfect 'white-point only' or 'black-point only' version is posible it has not been implemented at this time.
Auto-Level - perfect mathematical normalizationThe "
FUTURE: We actually need three modes of operation... synced color channels with 'alpha' (and 'read') masking. synced channels (as defined by channel) (current default) individual separate channels (currently if -channel is set by user)It is a pure-mathematical histogram stretch just as the manual Level Operator is. That is, the minimum will be adjusted to zero and maximum to Quantum range, and a linear equation is used to adjust all other values in the image. It does not use 'histogram bins' or any other 'grouping of values' that other methods may use for either determining the levels to be used, or other histogram adjustments.
Normalise and other Histogram operators are really grayscale operators,In actual fact, "
caution is needed when using it with color images.
Histogram RedistributionHistogram redistribution is a non-linear technique that redistributes the bins in a histogram in order to achieve some particular shape. The two most common shapes are uniform (flat) and Gaussian (bell-shaped), although Hyperbolic and Rayleigh are other types of distributions have also been used.
Equalize - Uniform Histogram RedistributionFor the case of an uniform distribution, the histogram bins are shifted, spaced and combined so that on average the histogram has a flat or constant height across the whole range. This is called histogram equalization. The IM function, "
Gaussian RedistributionEqualizing a histogram is not the only way of changing the histogram distribution of an image. Actually it isn't normally very useful, except in computer vision applications. Here is the same image, but transformed so its histogram has a Gaussian (bell-shaped) distribution. The values used here are a 60% gray mean, with a 60 sigma roll-off to either side of that mean.
Histogram Redistribution MethodologySo how does this type of direct histogram adjustment work? Basically it computes the histogram of the current image and that of the desired distribution. It then works out how the graylevel value of each 'bin' needs to be changed so that the counts in the bins best follow the desired distribution. Some bins may be shifted darker, while others may be shifted lighter. This is actually quite an involved process, so lets go though it step by step.
First, we need to get the actual histogram data from ImageMagick, rather than a graphic image of the histogram. Note that the data is from all the color values, combined into a grayscale. This was done so as to distribute all the channels together, and adjust the image overall brightness to follow to the desired curve.
DIY Level Adjustments
Mathematical Linear Histogram AdjustmentsThe various basic forms of Level Adjustments shown above linearly adjust the colors of the image. These changes can be applied mathematically as well. For example by multiplying the image with a specific color, we set all pure white areas to that color. So lets just read in our image, create an image containing the color we want, then multiply the original image with this color using the IM free-form "
result = 1-(1-color)*(1-intensity)This formula negates the colors, multiples the image with the negated color wanted, and negates the image back again. The result is tinting of the black side of the gray scale, leaving white unchanged. gnuplot" histogram graph of the remapping formula is also displayed in the above for your reference. With a slightly more complicated formula you can linearly replace both the '
Mathematical Non-linear Histogram AdjustmentsWhile linear color adjustments are important, and faster methods are available, there are many situations where a linear 'level' adjustment, is not what is wanted, and this is where the "
'Curves' AdjustmentsNormally in a graphical photo editor you would be presented with a histogram 'curves' chart such as I have shown to the left. The user can then edit the 'curve' by moving four (or more) control points, and the histogram adjustment function will follow those points. The control points generally specify that the first grayscale level is after adjustment to become the second grayscale level. So a point like 0.0,0.2 basically means that a 0% gray (black) should after adjustment be a 20% gray level. Now IM does not allow you to directly specify 'control points' to generate a 'curve' adjustment, what it wants is the mathematical formula of that 'curve' generated. Lucky for us there are programs that can generate that curve formula from the control points, including "
Uniformly Color Tinting ImagesTypically tinting an image is achieved by blending the image with a color by a certain amount. This can be done using an Evaluate Operator or Blend Images techniques, but these are not simple to use. Lucky for us a simpler method of bleeding an uniform color into an image is available by using the "
Midtone Color TintingWhile the Colorize operator applies the "
Sepia Tone ColoringA special photographic recoloring technique, "
Duotone EffectA 'duotone' is a printing method where you mix the grayscale of an image (black ink) with some other color to produce a better result, with a limited budget or printing equipment. For example the reason all the old photos you see today have a sepia-tone look about them, is because sepia-tone inks survived and did not deteriorate, or fade with time. Other 'black and white' images formats faded into uselessness. See the Sepia Tone Operator above. Another duotone technique known as 'Cyanotype' (more commonly known as 'blue-prints') became widely used as method of making large scale copies of the original black and white architect drawings. Remember this tenchique was used long before the invention of lazers and from that photo-copying (and Xerox). For more information see the Wikipedia entry for Duotone, also Fake duotones vs Real duotones. The above Tint Operator however produces a reasonable facsimile of the duotone effect, just as it did for a sepia-tone like effect above.
Color Tinting, DIYOne of the biggest problems with "
Color Tinting OverlayThe special Alpha Composition methods '
Global Color Modifiers
Modulate Brightness, Saturation, and HueThe "
Hue ModulationThe final value, Hue, is actually much more useful. It rotates the colors of the image, in a cyclic manner. To achieve this the Hue value given produces a 'modulus addition', rather than a multiplication. However be warned that the hue is rotated using a percentage, and not by an angle. This may seem weird but "
These types of operations and more can also be applied using advanced Color Space techniques, such as using in Recolor Matrix Operator (below), but for basic 'modulation' of an image, this operator greatly simplifies things. For primary color swapping, either Recolor Matrix Operator, or channel swapping (see Separate/Combine Operators), is probably more accurate technique. Though it is much less versatile. See also Hald Color Lookup Tables for a method by which you can save color change variations, especially changes in Hue, for later reuse.
Modulate DIYYou can if really want to "Do It Yourself". You basically magick the image into the appropriate color space, modify the values, and magick back. Remember that in HSL Color Space, the Green channel holds the Saturation value, and the Blue channel holds the Luminance value. For example, here is the equivalent to a "
Modulate in Other ColorspacesThe biggest problem with "
Modulate in LCHab and other ColorspacesHue modulation (in HSL or HSB colorpsace) is actually regarded as rather crude. These colorspaces do not take into account a more realistic intensity of the colors. As such rotating between the hues 'blue' and 'yellow' will also generate very large brightness shifts. See Wikipedia: Disadvantages to HSL Colorspace. One alternative is to do a Luminance preserving rotation as described on the Grafica Obscura in the "Matrix Operations" Paper. This is complex as the color modifications are being done as part of the operation, as a single calculated matrix operation that is different depending on how much of a rotation is required. As of IM v6.8.4-7 the Modulate Operator can also handle the special colorspaces '
Color Matrix OperatorThe "
In this particular case no change is made to the image. The matrix forms a special array, known as an 'identity matrix'. By mixing up the rows you can use to swap the various channels around. For example here I swap the red and blue channel values.
You can use a larger matrix of up to a set of 6 rows and columns. These correspond to the channels: '
Color Matrix ExamplesSepia Color, or at least a linear form of that operation
Such as described on the Grafica Obscura web page.
For more information on using a color matrix see...
Solarize ColoringTo "
Recoloring Images with Lookup TablesWhile you can recolor images using the various histogram color adjustments as shown above, there is another technique for recoloring images, simply by 'looking up' the modified values from a pre-prepared color gradient, or "Color Look Up Tables" (Color LUT, or CLUT). There are two types of Color LUT's: simple one dimensional or 'per-channel' LUT's and 3d color LUT's. A channel LUT has three independent look-up tables: one each for the R G and B channels. Each entry in the channel LUT maps an input channel value to an output channel value. The red channel of the output image is only effected by the original red value of the input image. A 3D color LUT however allow the whole color to be replaces as a function of the whole input color. That is, the output value of the red channel can be dependent on any or all of the input red, green, and blue values. This is sometimes called channel cross-talk.
Color (Channel) Lookup TablesA common requirement of an image processing tool is the ability to replace the whole range of colors, from a pre-prepared table of colors. This allows you to magick images of one set of colors (generally gray-scale) into completely different set of colors, just by looking up its replacement color from a special image. Of course you do need a 'Look Up Table' image from which to read the replacement colors. For these first few examples, I choose to use a vertical gradient of colors for the LUT so that the IM "
Function to Color LUT ConversionThese pre-prepared "Lookup Table Images" (or LUTs) can also be used to greatly increase the speed of very complex and thus slow "
WARNING: the above is incomplete (edges have not been darkened)
CLUT and Transparency HandlingThe "
Hald 3D Color Lookup TablesAs of IM v6.5.3-4 you can now also use a full 3D Color Lookup Table which can be used to directly replace all the colors of multiple images. That is, instead of just looking up the value of each each color channel as a separate entity (as in the CLUT above), the whole color is used to lookup the new color. However a 3D color tables usually require special file formats to correct store the 3D array of color values. However by using a special arrangement of color values the 3D table can be stored into a 2D image known as a Hald Color LUT. This is just a normal image and as such ANY good image file format can be used to save a Hald 3D Color LUT. For more details and examples of HALD Images, see the official website Hald Images, Clut Technology. To generate a Hald 3D color table, use the '
Hald CLUT LimitationsUnlike the simpler 1 Dimensional gradient lookup using the CLUT Operator you can use a Hald CLUT to rotate colors. For example swap red and blue colors. It is a much more versatile CLUT method. However it is not as good for doing simpler things like coloring a gray-scale image, or doing a histogram adjustment of color values. It can also replace colors with transparent, or semi-transparent values, by saving such replacement colors in the Hald CLUT image. However this replacement lookup is by color only. You cannot use it to replace transparent colors in specific ways. It isn't after all a 4D color lookup hyper-cube!
Color Replacement using Hald CLUTNow as the whole color value is used to lookup the color replacement, you could also use this as a method of directly replacing all the colors in an image with some other color. However as IM currently does a linear interpolated lookup of the Hald, you will need to set the replacement color in all 8 neighbouring color cells of the 3D color cube.
Under ConstructionThis needs more work, and may need a 'nearest-neighbour' Hald Lookup setting (say using -interpolate), rather than a 3D linear interpolated lookup to work better for specific color replacement. Also some easy way of locating specific colors in a Hald (nearest-neighbour, or the 8 neighbours) would make this a lot easier. If you have ideas, suggestions, or better still small examples, then please contribute by mailing them to me, or the IM Discussion Forums Another idea is that if you have two images, the original and the converted, then it should be possible to fill-in a Hald CLUT image from the comparison of the two images. When the immediate colors have been filled in the rest of the color cube should be able to be at least roughly derived by curve fitting the colors that are present. That is, create a 4-D color surface from the color changes discovered. When complete than you can apply the Hald CLUT to any other image so as to either make the same color transformation (in either direction) to any other image.
Full Color Map ReplacementFUTURE: Replace all the colors in one color map with colors in another color map. Suggestions as to how to best do this is welcome, or programmers to implement some image color map function. One method may be to use ideas presented in Dithering with Symbols. The best known solution (but hardly ideal) is currently provided by Fred Weinhaus in is "
More color options yet to be looked at in detail... -contrast -brightness-contrast Color Cycling? -cycle shift colormap (for animations of fractals???) Chromaticity Color Points??? –white-point x,y –red-primary x,y –green-primary x,y –blue-primary x,y Thresholds (after negation) Specifically -white-threshold and -black-threshold