[ImageMagick] [sponsor]
Processing
Options
Usage
MagickWand
MagickCore
PerlMagick
Magick++
Unix
Windows
Unix
Mac OS X
Windows
Links

The citizens of Oz were quite content with their benefactor, the all-powerful Wizard. They accepted his wisdom and benevolence without ever questioning the who, why, and where of his power. Like the citizens of Oz, if you feel comfortable that ImageMagick can help you convert, edit, or compose your images without knowing what goes on behind the curtain, feel free to skip this section. However, if you want to know more about the software and algorithms behind ImageMagick, read on. To fully benefit from this discussion, you should be comfortable with image nomenclature and be familiar with computer programming.

Architecture Overview

An image typically consists of a rectangular region of pixels and metadata. To convert, edit, or compose an image in an efficient manner we need convenient access to any pixel anywhere within the region (and sometimes outside the region). And in the case of an image sequence, we need access to any pixel of any region of any image in the sequence. However, there are hundreds of image formats such JPEG, TIFF, PNG, GIF, etc., that makes it difficult to access pixels on demand. Within these formats we find differences in:

In addition, some image pixels may require attenuation, some formats permit more than one frame, and some formats contain vector graphics that must first be rasterized (converted from vector to pixels).

An efficient implementation of an image processing algorithm may require we get or set:

In addition, some images include a clip mask that define which pixels are eligible to be updated. Pixels outside the area defined by the clip mask remain untouched.

Given the varied image formats and image processing requirements, we implemented the ImageMagick pixel cache to provide convenient sequential or parallel access to any pixel on demand anywhere inside the image region (we call these authentic pixels) and from any image in a sequence. In addition, the pixel cache permits access to pixels outside the boundaries defined by the image (we call these virtual pixels).

In addition to pixels, images have a plethora of image properties and profiles. Properties include the well known items such as width, height, depth, and colorspace. An image may have optional properties which might include the image author, a comment, a create date, and others. Some images also include profiles for color management, or EXIF, IPTC, 8BIM, or XMP informational profiles. ImageMagick provides command line options and programming methods to get, set, or view image properties or profiles or apply profiles.

ImageMagick consists of more than 400,000 lines of C code and optionally depends on several million lines of code in dependent libraries (e.g. JPEG, PNG, TIFF libraries). Given that, one might expect a huge architecture document. However, a great majority of image processing is simply accessing pixels and its metadata and our simple and elegant implementation makes this easy for the ImageMagick developer. We discuss the implementation of the pixel cache and getting and setting image properties and profiles in the next few sections. Next, we discuss using ImageMagick within a thread of execution. In the final sections, we discuss image coders to read or write a particular image format followed by a few words on creating a filter to access or update pixels based on your custom requirements.

The Pixel Cache

The ImageMagick pixel cache is a repository for image pixels with up to 5 channels. The first 4 channels are stored contiguously and an optional second area follows with 1 channel. The channels are at the depth specified when ImageMagick was built. The channel depths are 8 bits-per-pixel component for the Q8 version of ImageMagick, 16 bits-per-pixel component for the Q16 version, and 32 bits-per-pixel component for the Q32 version. By default pixel components are unsigned quantities, however, if you use the high dynamic-range version of ImageMagick, the components are 32-bit floating point. The primary 4 channels can hold any value but typically contain red, green, blue, and alpha intensities or cyan, magenta, yellow, and alpha intensities. The optional fifth channel contains the colormap indexes for colormapped images or the black channel for CMYK images. The pixel cache storage may be heap memory, anonymous memory mapped memory, disk-backed memory mapped, or on disk. The pixel cache is reference-counted. Only the cache properties are copied when the cache is cloned. The cache pixels are subsequently copied when you signal your intention to update any of the pixels.

Create the Pixel Cache

The pixel cache is associated with an image when it is created and it is initialized when you try to get or put pixels. Here are three common methods to associate a pixel cache with an image:

Create an image canvas initialized to the background color:

image=AllocateImage(image_info); if (SetImageExtent(image,640,480) == MagickFalse) { /* an exception was thrown */ } (void) QueryMagickColor("red",&image->background_color,&image->exception); SetImageBackgroundColor(image);

Create an image from a JPEG image on disk:

(void) strcpy(image_info->filename,"image.jpg"): image=ReadImage(image_info,exception); if (image == (Image *) NULL) { /* an exception was thrown */ }

Create an image from a memory based image:

image=BlobToImage(blob_info,blob,extent,exception); if (image == (Image *) NULL) { /* an exception was thrown */ }

In our discussion of the pixel cache, we use the MagickCore API to illustrate our points, however, the principles are the same for other program interfaces to ImageMagick.

When the pixel cache is initialized, pixels are scaled from whatever bit depth they originated from to that required by the pixel cache. For example, a 1-channel 1-bit monochrome PBM image is scaled to a 4 channel 8-bit RGBA image, if you are using the Q8 version of ImageMagick, and 16-bit RGBA for the Q16 version. You can determine which version you have with the ‑version option:

$magick> identify -versionVersion: ImageMagick 6.6.0-0 2010-02-21 Q16 http://www.imagemagick.org

As you can see, the convenience of the pixel cache sometimes comes with a trade-off in storage (e.g. storing a 1-bit monochrome image as 16-bit RGBA is wasteful) and speed (i.e. storing the entire image in memory is generally slower than accessing one scanline of pixels at a time). In most cases, the benefits of the pixel cache typically outweigh any disadvantages.

Access the Pixel Cache

Once the pixel cache is associated with an image, you typically want to get, update, or put pixels into it. We refer to pixels inside the image region as authentic pixels and outside the region as virtual pixels. Use these methods to access the pixels in the cache:

Here is a typical MagickCore code snippet for manipulating pixels in the pixel cache. In our example, we copy pixels from the input image to the output image and decrease the intensity by 10%:

  long
    x,
    y;

  const PixelPacket
    *p;

  PixelPacket
    *q;

  destination=CloneImage(source,source->columns,source->rows,MagickTrue,exception);
  if (destination  == (Image *) NULL)
    { /* an exception was thrown */ }
  for (y=0; y < (long) source->rows; y++)
  {
    p=GetVirtualPixels(source,0,y,source->columns,1,exception);
    q=GetAuthenticPixels(destination,0,y,destination->columns,1,exception);
    if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)
      break;
    for (x=0; x < (long) source->columns; x++)
    {
      q->red=90*p->red/100;
      q->green=90*p->green/100;
      q->blue=90*p->blue/100;
      q->opacity=90*p->opacity/100;
      p++;
      q++;
    }
    if (SyncAuthenticPixels(destination,exception) == MagickFalse)
      break;
  }
  if (y < (long) source->rows)
    { /* an exception was thrown */ }

When we first create the destination image by cloning the source image, the pixel cache pixels are not copied. They are only copied when you signal your intentions to modify the pixel cache by calling GetAuthenticPixels() or QueueAuthenticPixels(). Use QueueAuthenticPixels() if you want to set new pixel values rather than update existing ones. Finally, use SyncAuthenticPixels() to ensure any updated pixels are pushed to the pixel cache.

Recall how we mentioned that the indexes of a colormapped image or the black channel of a CMYK image are stored separately. Use GetVirtualIndexes() (to read the indexes) or GetAuthenticIndexes() (to update the indexes) to gain access to this channel. For example, to print the colormap indexes, use:

  const IndexPacket
    *indexes;

  for (y=0; y < (long) source->rows; y++)
  {
    p=GetVirtualPixels(source,0,y,source->columns,1);
    if (p == (const PixelPacket *) NULL)
      break;
    indexes=GetVirtualIndexes(source);
    for (x=0; x < (long) source->columns; x++)
      (void) printf("%d\n",indexes[x];
  }
  if (y < (long) source->rows)
    /* an exception was thrown */

The pixel cache manager decides whether to give you direct or indirect access to the image pixels. In some cases the pixels are staged to an intermediate buffer-- and that is why you must call SyncAuthenticPixels() to ensure this buffer is pushed out to the pixel cache to guarantee the corresponding pixels in the cache are updated. For this reason we recommend that you only read or update a scanline or a few scanlines of pixels at a time. However, you can get any rectangular region of pixels you want. GetAuthenticPixels() requires that the region you request is within the bounds of the image area. For a 640 by 480 image, you can get a scanline of 640 pixels at row 479 but if you ask for a scanline at row 480, an exception is returned (rows are numbered starting at 0). GetVirtualPixels() does not have this constraint. For example,

  p=GetVirtualPixels(source,-3,3,source->columns+7,7,exception);

gives you the pixels you asked for without complaint, even though some are not within the confines of the image region.

Virtual Pixels

Access to the virtual pixels are controlled by the SetImageVirtualPixelMethod() method from the MagickCore API or the ‑virtual‑pixel option from the command line. The methods include:

  background:           the area surrounding the image is the background color
  black:                the area surrounding the image is black
  checker-tile:         alternate squares with image and background color
  dither:               non-random 32x32 dithered pattern
  edge:                 extend the edge pixel toward infinity
  gray:                 the area surrounding the image is gray
  horizontal-tile:      horizontally tile the image, background color above/below
  horizontal-tile-edge: horizontally tile the image and replicate the side edge pixels
  mirror:               mirror tile the image
  random:               choose a random pixel from the image
  tile:                 tile the image (default)
  transparent:          the area surrounding the image is transparent blackness
  vertical-tile:        vertically tile the image, sides are background color
  vertical-tile-edge:   vertically tile the image and replicate the side edge pixels
  white:                the area surrounding the image is white

There is a plethora of image processing algorithms that require a neighborhood of pixels about a pixel of interest. There is typically a caveat concerning how to handle pixels around the image boundaries, known as edge pixels. With virtual pixels, you do not need to concern yourself about special edge processing other than choosing which virtual pixel method is most appropriate for your algorithm.

Cache Storage and Resource Requirements

Recall that this simple and elegant design of the ImageMagick pixel cache comes at a cost in terms of storage and processing speed. The pixel cache storage requirements scales with the area of the image and the bit depth of the pixel components. For example, if we have a 640 by 480 image and we are using the Q16 version of ImageMagick, the pixel cache consumes image width * height * bit-depth / 8 * channels bytes or approximately 2.3 mebibytes (i.e. 640 * 480 * 2 * 4). Not too bad, but what if your image is 25000 by 25000 pixels? The pixel cache requires approximately 4.7 gibibytes of storage. Ouch. ImageMagick accounts for possible huge storage requirements by caching large images to disk rather than memory. Typically the pixel cache is stored in memory using heap memory. If heap memory is exhausted, pixels are stored in in an anonymous map; if the anonymous memory map is exhausted, we create the pixel cache on disk and attempt to memory-map it; and if memory-map memory is exhausted, we simply use standard disk I/O. Disk storage is cheap but it is also very slow, upwards of 1000 times slower than memory. We can get some speed improvements, up to 5 times, if we use memory mapping to the disk-based cache. These decisions about storage are made automagically by the pixel cache manager negotiating with the operating system. However, you can influence how the pixel cache manager allocates the pixel cache with cache resource limits. The limits include:

files
maximum number of open pixel cache files. When this limit is exceeded, any subsequent pixels cached to disk are closed and reopened on demand. This behavior permits a large number of images to be accessed simultaneously on disk, but with a speed penalty due to repeated open/close calls.
area
maximum area in bytes of any one image that can reside in the pixel cache memory. If this limit is exceeded, the image is automagically cached to disk.
memory
maximum amount of memory in bytes to allocate for the pixel cache from the anonymous mapped memory or the heap.
map
maximum amount of memory map in bytes to allocate for the pixel cache.
disk
maximum amount of disk space in bytes permitted for use by the pixel cache. If this limit is exceeded, the pixel cache is not created and a fatal exception is thrown.

To determine the current setting of these limits, use this command:

$magick> identify -list resource

File        Area      Memory         Map        Disk  Thread        Time
------------------------------------------------------------------------
 768   11.551GiB   8.6631GiB   23.102GiB       16EiB       8   unlimited

You can set these limits either with environment variables, the -limit command line option, or the SetMagickResourceLimit() MagickCore API method. As an example, our online web interface to ImageMagick, ImageMagick Studio, has an area limit of 64 mebibytes, a memory limit of 128 mebibytes and a map limit of 256 mebibytes and a disk limit of 1 gibibytes. Since we process multiple simultaneous sessions, we don't want any one session consuming all the available memory. Instead large images are cached to disk. If the image is too large and exceeds the pixel cache disk limit, the program exits. In addition, we place a 60 second time limit to prevent any run-away processing tasks.

Note, the cache limits are global, meaning if you create several images, the combined resource requirements are compared to the limit to determine the pixel cache storage disposition.

Cache Views

GetVirtualPixels(), GetAuthenticPixels(), QueueAuthenticPixels(), and SyncAuthenticPixels() from the MagickCore API can only deal with one pixel cache area per image at a time. Suppose you want to access the first and last scanline from the same image at the same time? The solution is to use a cache view. A cache view permits you to access as many areas simultaneously in the pixel cache as you require. The cache view methods behave like the previous methods except you must first open a view and close it when you are finished with it. Here is a snippet of MagickCore code that permits us to access two areas of an image simultaneously:

  CacheView
    *view_1,
    *view_2;

  view_1=OpenCacheView(source);
  view_2=OpenCacheView(source);
  for (y=0; y < (long) source->rows; y++)
  {
    u=GetCacheViewVirtualPixels(view_1,0,y,source->columns,1,exception);
    v=GetCacheViewVirtualPixels(view_2,0,source->rows-y-1,source->columns,1,exception);
    if ((u == (const PixelPacket *) NULL) || (v == (const PixelPacket *) NULL))
      break;
    for (x=0; x < (long) source->columns; x++)
    {
      /* do something with u & v here */
    }
  }
  view_1=CloseCacheView(view_1);
  view_2=CloseCacheView(view_2);
  if (y < (long) source->rows)
    { /* an exception was thrown */ }

Magick Persistent Cache Format

Recall that each image format is decoded by ImageMagick and the pixels are deposited in the pixel cache. If you write an image, the pixels are read from the pixel cache and encoded as required by the format you are writing (e.g. GIF, PNG, etc.). The Magick Persistent Cache (MPC) format is designed to eliminate the overhead of decoding and encoding pixels to and from an image format. MPC writes two files. One, with the extension .mpc, retains all the properties associated with the image or image sequence (e.g. width, height, colorspace, etc.) and the second, with the extension .cache, is the pixel cache in the native raw format. When reading an MPC image file, ImageMagick reads the image properties and memory maps the pixel cache on disk eliminating the need for decoding the image pixels. The tradeoff is in disk space. MPC is generally larger in file size than most other image formats.

Best Practices

Although you can request any pixel from the pixel cache, any block of pixels, any scanline, multiple scanlines, any row, or multiple rows with the GetVirtualPixels(), GetAuthenticPixels(), QueueAuthenticPixels, GetCacheViewVirtualPixels(), GetCacheViewAuthenticPixels(), and QueueCacheViewAuthenticPixels() methods, ImageMagick is optimized to return a few pixels or a few pixels rows at time. There are additional optimizations if you request a single scanline or a few scanlines at a time. These methods also permit random access to the pixel cache, however, ImageMagick is optimized for sequential access.

If you update pixels returned from GetAuthenticPixels() or GetCacheViewAuthenticPixels(), don't forget to call SyncAuthenticPixels() or SyncCacheViewAuthenticPixels() respectively to ensure your changes are synchronized with the pixel cache.

Use QueueAuthenticPixels() or QueueCacheViewAuthenticPixels() if you are setting an initial pixel value. The GetAuthenticPixels() or GetCacheViewAuthenticPixels() method reads pixels from the cache and if you are setting an initial pixel value, this read is unnecessary. Don't forget to call SyncAuthenticPixels() or SyncCacheViewAuthenticPixels() respectively to push your updates to the pixel cache.

GetVirtualPixels(), GetAuthenticPixels(), QueueAuthenticPixels(), and SyncAuthenticPixels() are slightly more efficient than their cache view counter-parts. However, cache views are required if you need access to more than one region of the image simultaneously or if more than one thread of execution is accessing the image.

You can request pixels outside the bounds of the image with GetVirtualPixels() or GetCacheViewVirtualPixels(), however, it is more efficient to request pixels within the confines of the image region.

Although you can force the pixel cache to disk using appropriate resource limits, disk access can be upwards of 1000 times slower than memory access. For fast, efficient, access to the pixel cache, try to keep the pixel cache in heap memory or anonymous mapped memory.

The ImageMagick Q16 version of ImageMagick permits you to read and write 16 bit images without scaling but the pixel cache consumes twice as much resources as the Q8 version. If your system has constrained memory or disk resources, consider the Q8 version of ImageMagick. In addition, the Q8 version typically executes faster than the Q16 version.

A great majority of image formats and algorithms restrict themselves to a fixed range of pixel values from 0 to some maximum value, for example, the Q16 version of ImageMagick permit intensities from 0 to 65535. High dynamic-range imaging (HDRI), however, permits a far greater dynamic range of exposures (i.e. a large difference between light and dark areas) than standard digital imaging techniques. HDRI accurately represents the wide range of intensity levels found in real scenes ranging from the brightest direct sunlight to the deepest darkest shadows. Enable HDRI at ImageMagick build time to deal with high dynamic-range images, but be mindful that each pixel component is a 32-bit floating point value. In addition, pixel values are not clamped by default so some algorithms may perform differently than the non-HDRI version.

If you are dealing with large images, make sure the pixel cache is written to a disk area with plenty of free space. Under Unix, this is typically /tmp and for Windows, c:/temp. You can tell ImageMagick to write the pixel cache to an alternate location with the MAGICK_TEMPORARY_PATH environment variable. For example,

$magick> export MAGICK_TEMPORARY_PATH=/data/magick

If you plan on processing the same image many times, consider the MPC format. Reading a MPC image has near-zero overhead because its in the native pixel cache format eliminating the need for decoding the image pixels. Here is an example:

$magick> convert image.tif image.mpc $magick> convert image.mpc -crop 100x100+0+0 +repage 1.png $magick> convert image.mpc -crop 100x100+100+0 +repage 2.png $magick> convert image.mpc -crop 100x100+200+0 +repage 3.png

MPC is ideal for web sites. It reduces the overhead of reading and writing an image. We use it exclusively at our online image studio.

Streaming Pixels

ImageMagick provides for streaming pixels as they are read from or written to an image. This has several advantages over the pixel cache. The time and resources consumed by the pixel cache scale with the area of an image, whereas the pixel stream resources scale with the width of an image. The disadvantage is the pixels must be consumed as they are streamed so there is no persistence.

Use ReadStream() or WriteStream() with an appropriate callback method in your MagickCore program to consume the pixels as they are streaming. Here's an abbreviated example of using ReadStream:

static size_t StreamHandler(const Image *image,const void *pixels,
  const size_t columns)
{
  /* process pixels here */
  return(columns);
}

...
/* invoke the pixel stream here */
image=ReadStream(image_info,&StreamHandler,exception);

We also provide a lightweight tool, stream, to stream one or more pixel components of the image or portion of the image to your choice of storage formats. It writes the pixel components as they are read from the input image a row at a time making stream desirable when working with large images or when you require raw pixel components.

Image Properties and Profiles

Images have metadata associated with them in the form of properties (e.g. width, height, description, etc.) and profiles (e.g. EXIF, IPTC, color management). ImageMagick provides convenient methods to get, set, or update image properties and get, set, update, or apply profiles. Some of the more popular image properties are associated with the Image structure in the MagickCore API. For example:

  (void) printf("image width: %lu, height: %lu\n",image->columns,image->rows);

For a great majority of image properties, such as an image comment or description, we use the GetImageProperty() and SetImageProperty() methods. Here we set a property and fetch it right back:

  const char
    *comment;

  (void) SetImageProperty(image,"comment","This space for rent");
  comment=GetImageProperty(image,"comment");
  if (comment == (const char *) NULL)
    (void) printf("Image comment: %s\n",comment);

ImageMagick supports artifacts with the GetImageArtifact() and SetImageArtifact() methods. Artifacts are stealth properties that are not exported to image formats (e.g. PNG) and they do not display when identifying an image.

Image profiles are handled with GetImageProfile(), SetImageProfile(), and ProfileImage() methods. Here we set a profile and fetch it right back:

  StringInfo
    *profile;

  profile=AcquireStringInfo(length);
  SetStringInfoDatum(profile,my_exif_profile);
  (void) SetImageProfile(image,"EXIF",profile);
  DestroyStringInfo(profile);
  profile=GetImageProfile(image,"EXIF");
  if (profile != (StringInfo *) NULL)
    (void) PrintStringInfo(stdout,"EXIF",profile);

Large Image Support

ImageMagick can read, process, or write mega-, giga-, or tera-pixel image sizes. For example, here we resize an image to a quarter million pixels square:

$magick> convert logo: -resize 250000x250000 logo.miff

For large images, ImageMagick will more than likely create a pixel cache on disk. Make sure you have plenty of temporary disk space. If your default temporary disk partition is too small, tell ImageMagick to use another partition with plenty of free space. For example:

$magick> convert -define registry:temporary-path=/data/tmp logo: -resize 250000x250000 logo.miff

To ensure large images do not consume all the memory on your system, force the image pixels to memory-mapped disk with resource limits:

$magick> convert -define registry:temporary-path=/data/tmp -limit memory 16mb logo: -resize 250000x250000 logo.miff

Here we force all image pixels to disk:

$magick> convert -define registry:temporary-path=/data/tmp -limit area 0 logo: -resize 250000x250000 logo.miff

Caching pixels to disk is about 1000 times slower than memory. Expect long run times when processing large images with ImageMagick. You can monitor progress with this command:

$magick> convert -monitor -define registry:temporary-path=/data/tmp -limit area 0 logo: -resize 250000x250000 logo.miff

Threads of Execution

Many of ImageMagick's internal algorithms are threaded to take advantage of speed-ups offered by the dual and quad-core processor technologies. However, you are welcome to use ImageMagick algorithms in your threads of execution with the exception of the MagickCore's GetVirtualPixels(), GetAuthenticPixels(), QueueAuthenticPixels(), or SyncAuthenticPixels() pixel cache methods. These methods are intended for one thread of execution only. To access the pixel cache with more than one thread of execution, use a cache view. We do this for the CompositeImage() method, for example. Suppose we want to composite a single image over a different image in each thread of execution. If we use GetVirtualPixels(), the results are unpredictable because multiple threads would likely be asking for different areas of the pixel cache simultaneously. Instead we use GetCacheViewVirtualPixels() which creates a unique view for each thread of execution ensuring our program behaves properly regardless of how many threads are invoked. The other program interfaces, such as the MagickWand API, are completely thread safe so there are no special precautions for threads of execution.

Here is an example of how ImageMagick can take advantage of threads of execution with the OpenMP programming paradigm:

{
  CacheView
    *image_view;

  long
    y;

  MagickBooleanType
    status;

  status=MagickTrue;
  image_view=AcquireCacheView(image);
  #pragma omp parallel for schedule(dynamic,4) shared(status)
  for (y=0; y < (long) image->rows; y++)
  {
    register IndexPacket
      *indexes;

    register long
      x;

    register PixelPacket
      *q;

    if (status == MagickFalse)
      continue;
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
    if (q == (PixelPacket *) NULL)
      {
        status=MagickFalse;
        continue;
      }
    indexes=GetCacheViewAuthenticIndexQueue(image_view);
    for (x=0; x < (long) image->columns; x++)
    {
      q->red= ...
      q->green= ...
      q->blue= ...
      q->opacity= ...
      if (indexes != (IndexPacket *) NULL)
        indexes[x]= ...
      q++;
    }
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
      status=MagickFalse;
  }
  image_view=DestroyCacheView(image_view);
  if (status == MagickFalse)
    perror("something went wrong");
}

If you call the ImageMagick API from your OpenMP-enabled application and you intend to dynamically increase the number of threads available in subsequent parallel regions, be sure to perform the increase before you call the API otherwise ImageMagick may fault.

Heterogeneous Distributed Processing

ImageMagick includes support for heterogeneous distributed processing with the OpenCL framework. OpenCL kernels within ImageMagick permit image processing algorithms to execute across heterogeneous platforms consisting of CPUs, GPUs, and other processors. Depending on your platform, speed-ups can be an order of magnitude faster than the traditional single CPU.

First verify that your version of ImageMagick includes support for the OpenCL feature:

$magick> identify -versionFeatures: OpenMP OpenCL

If so, run this command to realize a significant speed-up for image convolution:

$magick> convert image.png convolve '-1, -1, -1, -1, 9, -1, -1, -1, -1' convolve.png

If an accelerator is not available or if the accelerator fails to respond, ImageMagick reverts to the non-accelerated convolution algorithm.

Here is an example OpenCL kernel that convolves an image:

static inline long ClampToCanvas(const long offset,const ulong range)
{
  if (offset < 0L)
    return(0L);
  if (offset >= range)
    return((long) (range-1L));
  return(offset);
}

static inline CLQuantum ClampToQuantum(const double value)
{
  if (value < 0.0)
    return((CLQuantum) 0);
  if (value >= (double) QuantumRange)
    return((CLQuantum) QuantumRange);
  return((CLQuantum) (value+0.5));
}

__kernel void Convolve(const __global CLPixelType *source,__constant double *filter,
  const ulong width,const ulong height,__global CLPixelType *destination)
{
  const ulong columns = get_global_size(0);
  const ulong rows = get_global_size(1);

  const long x = get_global_id(0);
  const long y = get_global_id(1);

  const double scale = (1.0/QuantumRange);
  const long mid_width = (width-1)/2;
  const long mid_height = (height-1)/2;
  double4 sum = { 0.0, 0.0, 0.0, 0.0 };
  double gamma = 0.0;
  register ulong i = 0;

  for (long v=(-mid_height); v <= mid_height; v++)
  {
    for (long u=(-mid_width); u <= mid_width; u++)
    {
      register const ulong index=ClampToCanvas(y+v,rows)*columns+ClampToCanvas(x+u,columns);
      const double alpha=scale*(QuantumRange-source[index].w);
      sum.x+=alpha*filter[i]*source[index].x;
      sum.y+=alpha*filter[i]*source[index].y;
      sum.z+=alpha*filter[i]*source[index].z;
      sum.w+=filter[i]*source[index].w;
      gamma+=alpha*filter[i];
      i++;
    }
  }

  gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
  const ulong index=y*columns+x;
  destination[index].x=ClampToQuantum(gamma*sum.x);
  destination[index].y=ClampToQuantum(gamma*sum.y);
  destination[index].z=ClampToQuantum(gamma*sum.z);
  destination[index].w=ClampToQuantum(sum.w);
};

See filters/convolve.c for a complete implementation of image convolution with an OpenCL kernel.

Custom Image Coders

An image coder (i.e. encoder / decoder) is responsible for registering, optionally classifying, optionally reading, optionally writing, and unregistering one image format (e.g. PNG, GIF, JPEG, etc.). Registering an image coder alerts ImageMagick a particular format is available to read or write. While unregistering tells ImageMagick the format is no longer available. The classifying method looks at the first few bytes of an image and determines if the image is in the expected format. The reader sets the image size, colorspace, and other properties and loads the pixel cache with the pixels. The reader returns a single image or an image sequence (if the format supports multiple images per file), or if an error occurs, an exception and a null image. The writer does the reverse. It takes the image properties and unloads the pixel cache and writes them as required by the image format.

Here is a listing of a sample custom coder. It reads and writes images in the MGK image format which is simply an ID followed by the image width and height followed by the RGB pixel values.

/*
  Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/colorspace.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"

/*
  Forward declarations.
*/
static MagickBooleanType
  WriteMGKImage(const ImageInfo *,Image *);

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   I s M G K                                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  IsMGK() returns MagickTrue if the image format type, identified by the
%  magick string, is MGK.
%
%  The format of the IsMGK method is:
%
%      MagickBooleanType IsMGK(const unsigned char *magick,const size_t length)
%
%  A description of each parameter follows:
%
%    o magick: This string is generally the first few bytes of an image file
%      or blob.
%
%    o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsMGK(const unsigned char *magick,const size_t length)
{
  if (length < 7)
    return(MagickFalse);
  if (LocaleNCompare((char *) magick,"id=mgk",7) == 0)
    return(MagickTrue);
  return(MagickFalse);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d M G K I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadMGKImage() reads a MGK image file and returns it.  It allocates
%  the memory necessary for the new Image structure and returns a pointer to
%  the new image.
%
%  The format of the ReadMGKImage method is:
%
%      Image *ReadMGKImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMGKImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  char
    buffer[MaxTextExtent];

  Image
    *image;

  long
    y;

  MagickBooleanType
    status;

  register long
    x;

  register PixelPacket
    *q;

  register unsigned char
    *p;

  ssize_t
    count;

  unsigned char
    *pixels;

  unsigned long
    columns,
    rows;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Read MGK image.
  */
  (void) ReadBlobString(image,buffer);  /* read magic number */
  if (IsMGK(buffer,7) == MagickFalse)
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  (void) ReadBlobString(image,buffer);
  count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows);
  if (count <= 0)
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  do
  {
    /*
      Initialize image structure.
    */
    image->columns=columns;
    image->rows=rows;
    image->depth=8;
    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    /*
      Convert MGK raster image to pixel packets.
    */
    if (SetImageExtent(image,0,0) == MagickFalse)
      {
        InheritException(exception,&image->exception);
        return(DestroyImageList(image));
      }
    pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns,3UL*sizeof(*pixels));
    if (pixels == (unsigned char *) NULL)
      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
    for (y=0; y < (long) image->rows; y++)
    {
      count=(ssize_t) ReadBlob(image,(size_t) (3*image->columns),pixels);
      if (count != (ssize_t) (3*image->columns))
        ThrowReaderException(CorruptImageError,"UnableToReadImageData");
      p=pixels;
      q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
      if (q == (PixelPacket *) NULL)
        break;
      for (x=0; x < (long) image->columns; x++)
      {
        q->red=ScaleCharToQuantum(*p++);
        q->green=ScaleCharToQuantum(*p++);
        q->blue=ScaleCharToQuantum(*p++);
        q++;
      }
      if (SyncAuthenticPixels(image,exception) == MagickFalse)
        break;
      if ((image->previous == (Image *) NULL) &&
          (SetImageProgress(image,LoadImageTag,y,image>>rows) == MagickFalse))
        break;
    }
    pixels=(unsigned char *) RelinquishMagickMemory(pixels);
    if (EOFBlob(image) != MagickFalse)
      {
        ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",image->filename);
        break;
      }
    /*
      Proceed to next image.
    */
    if (image_info->number_scenes != 0)
      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    *buffer='\0';
    (void) ReadBlobString(image,buffer);
    count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows);
    if (count != 0)
      {
        /*
          Allocate next image structure.
        */
        AcquireNextImage(image_info,image);
        if (GetNextImageInList(image) == (Image *) NULL)
          {
            image=DestroyImageList(image);
            return((Image *) NULL);
          }
        image=SyncNextImageInList(image);
        status=SetImageProgress(image,LoadImageTag,TellBlob(image),GetBlobSize(image));
        if (status == MagickFalse)
          break;
      }
  } while (count != 0);
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e g i s t e r M G K I m a g e                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  RegisterMGKImage() adds attributes for the MGK image format to
%  the list of supported formats.  The attributes include the image format
%  tag, a method to read and/or write the format, whether the format
%  supports the saving of more than one frame to the same file or blob,
%  whether the format supports native in-memory I/O, and a brief
%  description of the format.
%
%  The format of the RegisterMGKImage method is:
%
%      unsigned long RegisterMGKImage(void)
%
*/
ModuleExport unsigned long RegisterMGKImage(void)
{
  MagickInfo
    *entry;

  entry=SetMagickInfo("MGK");
  entry->decoder=(DecodeImageHandler *) ReadMGKImage;
  entry->encoder=(EncodeImageHandler *) WriteMGKImage;
  entry->magick=(IsImageFormatHandler *) IsMGK;
  entry->description=ConstantString("MGK");
  entry->module=ConstantString("MGK");
  (void) RegisterMagickInfo(entry);
  return(MagickImageCoderSignature);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   U n r e g i s t e r M G K I m a g e                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  UnregisterMGKImage() removes format registrations made by the
%  MGK module from the list of supported formats.
%
%  The format of the UnregisterMGKImage method is:
%
%      UnregisterMGKImage(void)
%
*/
ModuleExport void UnregisterMGKImage(void)
{
  (void) UnregisterMagickInfo("MGK");
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   W r i t e M G K I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  WriteMGKImage() writes an image to a file in red, green, and blue
%  MGK rasterfile format.
%
%  The format of the WriteMGKImage method is:
%
%      MagickBooleanType WriteMGKImage(const ImageInfo *image_info,Image *image)
%
%  A description of each parameter follows.
%
%    o image_info: the image info.
%
%    o image:  The image.
%
*/
static MagickBooleanType WriteMGKImage(const ImageInfo *image_info,Image *image)
{
  char
    buffer[MaxTextExtent];

  long
    y;

  MagickBooleanType
    status;

  MagickOffsetType
    scene;

  register const PixelPacket
    *p;

  register long
    x;

  register unsigned char
    *q;

  unsigned char
    *pixels;

  /*
    Open output image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
  if (status == MagickFalse)
    return(status);
  scene=0;
  do
  {
    /*
      Allocate memory for pixels.
    */
    if (image->colorspace != RGBColorspace)
      (void) SetImageColorspace(image,RGBColorspace);
    pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns,
      3UL*sizeof(*pixels));
    if (pixels == (unsigned char *) NULL)
      ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
    /*
      Initialize raster file header.
    */
    (void) WriteBlobString(image,"id=mgk\n");
    (void) FormatMagickString(buffer,MaxTextExtent,"%lu %lu\n",
      image->columns,image->rows);
    (void) WriteBlobString(image,buffer);
    for (y=0; y < (long) image->rows; y++)
    {
      p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
      if (p == (const PixelPacket *) NULL)
        break;
      q=pixels;
      for (x=0; x < (long) image->columns; x++)
      {
        *q++=ScaleQuantumToChar(p->red);
        *q++=ScaleQuantumToChar(p->green);
        *q++=ScaleQuantumToChar(p->blue);
        p++;
      }
      (void) WriteBlob(image,(size_t) (q-pixels),pixels);
      if ((image->previous == (Image *) NULL) &&
          (SetImageProgress(image,SaveImageTag,y,image->rows) == MagickFalse))
        break;
    }
    pixels=(unsigned char *) RelinquishMagickMemory(pixels);
    if (GetNextImageInList(image) == (Image *) NULL)
      break;
    image=SyncNextImageInList(image);
    status=SetImageProgress(image,SaveImagesTag,scene,
      GetImageListLength(image));
    if (status == MagickFalse)
      break;
    scene++;
  } while (image_info->adjoin != MagickFalse);
  (void) CloseBlob(image);
  return(MagickTrue);
}

To invoke the custom coder from the command line, use these commands:

$magick> convert logo: logo.mgk $magick> display logo.mgk

We provide the Magick Coder Kit to help you get started writing your own custom coder.

Custom Image Filters

ImageMagick provides a convenient mechanism for adding your own custom image processing algorithms. We call these image filters and they are invoked from the command line with the -process option or from the MagickCore API method ExecuteModuleProcess().

Here is a listing of a sample custom image filter. It computes a few statistics such as the pixel brightness and saturation mean and standard-deviation.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <math.h>
#include "magick/MagickCore.h"

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   a n a l y z e I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  analyzeImage() computes the brightness and saturation mean,  standard
%  deviation, kurtosis and skewness and stores these values as attributes 
%  of the image.
%
%  The format of the analyzeImage method is:
%
%      unsigned long analyzeImage(Image *images,const int argc,
%        char **argv,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image: the address of a structure of type Image.
%
%    o argc: Specifies a pointer to an integer describing the number of
%      elements in the argument vector.
%
%    o argv: Specifies a pointer to a text array containing the command line
%      arguments.
%
%    o exception: return any errors or warnings in this structure.
%
*/
ModuleExport unsigned long analyzeImage(Image **images,const int argc,
  const char **argv,ExceptionInfo *exception)
{
  char
    text[MaxTextExtent];

  double
    area,
    brightness,
    brightness_mean,
    brightness_standard_deviation,
    brightness_kurtosis,
    brightness_skewness,
    brightness_sum_x,
    brightness_sum_x2,
    brightness_sum_x3,
    brightness_sum_x4,
    hue,
    saturation,
    saturation_mean,
    saturation_standard_deviation,
    saturation_kurtosis,
    saturation_skewness,
    saturation_sum_x,
    saturation_sum_x2,
    saturation_sum_x3,
    saturation_sum_x4;

  Image
    *image;

  assert(images != (Image **) NULL);
  assert(*images != (Image *) NULL);
  assert((*images)->signature == MagickSignature);
  (void) argc;
  (void) argv;
  image=(*images);
  for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
  {
    CacheView
      *image_view;

    long
      y;

    MagickBooleanType
      status;

    brightness_sum_x=0.0;
    brightness_sum_x2=0.0;
    brightness_sum_x3=0.0;
    brightness_sum_x4=0.0;
    brightness_mean=0.0;
    brightness_standard_deviation=0.0;
    brightness_kurtosis=0.0;
    brightness_skewness=0.0;
    saturation_sum_x=0.0;
    saturation_sum_x2=0.0;
    saturation_sum_x3=0.0;
    saturation_sum_x4=0.0;
    saturation_mean=0.0;
    saturation_standard_deviation=0.0;
    saturation_kurtosis=0.0;
    saturation_skewness=0.0;
    area=0.0;
    status=MagickTrue;
    image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
    #pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
    for (y=0; y < (long) image->rows; y++)
    {
      register const PixelPacket
        *p;

      register long
        x;

      if (status == MagickFalse)
        continue;
      p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
      if (p == (const PixelPacket *) NULL)
        {
          status=MagickFalse;
          continue;
        }
      for (x=0; x < (long) image->columns; x++)
      {
        ConvertRGBToHSB(p->red,p->green,p->blue,&hue,&saturation,&brightness);
        brightness*=QuantumRange;
        brightness_sum_x+=brightness;
        brightness_sum_x2+=brightness*brightness;
        brightness_sum_x3+=brightness*brightness*brightness;
        brightness_sum_x4+=brightness*brightness*brightness*brightness;
        saturation*=QuantumRange;
        saturation_sum_x+=saturation;
        saturation_sum_x2+=saturation*saturation;
        saturation_sum_x3+=saturation*saturation*saturation;
        saturation_sum_x4+=saturation*saturation*saturation*saturation;
        area++;
        p++;
      }
    }
    image_view=DestroyCacheView(image_view);
    if (area <= 0.0)
      break;
    brightness_mean=brightness_sum_x/area;
    (void) FormatMagickString(text,MaxTextExtent,"%g",brightness_mean);
    (void) SetImageProperty(image,"filter:brightness:mean",text);
    brightness_standard_deviation=sqrt(brightness_sum_x2/area-(brightness_sum_x/
      area*brightness_sum_x/area));
    (void) FormatMagickString(text,MaxTextExtent,"%g",
      brightness_standard_deviation);
    (void) SetImageProperty(image,"filter:brightness:standard-deviation",text);
    if (brightness_standard_deviation != 0)
      brightness_kurtosis=(brightness_sum_x4/area-4.0*brightness_mean*
        brightness_sum_x3/area+6.0*brightness_mean*brightness_mean*
        brightness_sum_x2/area-3.0*brightness_mean*brightness_mean*
        brightness_mean*brightness_mean)/(brightness_standard_deviation*
        brightness_standard_deviation*brightness_standard_deviation*
        brightness_standard_deviation)-3.0;
    (void) FormatMagickString(text,MaxTextExtent,"%g",brightness_kurtosis);
    (void) SetImageProperty(image,"filter:brightness:kurtosis",text);
    if (brightness_standard_deviation != 0)
      brightness_skewness=(brightness_sum_x3/area-3.0*brightness_mean*
        brightness_sum_x2/area+2.0*brightness_mean*brightness_mean*
        brightness_mean)/(brightness_standard_deviation*
        brightness_standard_deviation*brightness_standard_deviation);
    (void) FormatMagickString(text,MaxTextExtent,"%g",brightness_skewness);
    (void) SetImageProperty(image,"filter:brightness:skewness",text);
    saturation_mean=saturation_sum_x/area;
    (void) FormatMagickString(text,MaxTextExtent,"%g",saturation_mean);
    (void) SetImageProperty(image,"filter:saturation:mean",text);
    saturation_standard_deviation=sqrt(saturation_sum_x2/area-(saturation_sum_x/
      area*saturation_sum_x/area));
    (void) FormatMagickString(text,MaxTextExtent,"%g",
      saturation_standard_deviation);
    (void) SetImageProperty(image,"filter:saturation:standard-deviation",text);
    if (saturation_standard_deviation != 0)
      saturation_kurtosis=(saturation_sum_x4/area-4.0*saturation_mean*
        saturation_sum_x3/area+6.0*saturation_mean*saturation_mean*
        saturation_sum_x2/area-3.0*saturation_mean*saturation_mean*
        saturation_mean*saturation_mean)/(saturation_standard_deviation*
        saturation_standard_deviation*saturation_standard_deviation*
        saturation_standard_deviation)-3.0;
    (void) FormatMagickString(text,MaxTextExtent,"%g",saturation_kurtosis);
    (void) SetImageProperty(image,"filter:saturation:kurtosis",text);
    if (saturation_standard_deviation != 0)
      saturation_skewness=(saturation_sum_x3/area-3.0*saturation_mean*
        saturation_sum_x2/area+2.0*saturation_mean*saturation_mean*
        saturation_mean)/(saturation_standard_deviation*
        saturation_standard_deviation*saturation_standard_deviation);
    (void) FormatMagickString(text,MaxTextExtent,"%g",saturation_skewness);
    (void) SetImageProperty(image,"filter:saturation:skewness",text);
  }
  return(MagickImageFilterSignature);
}

To invoke the custom filter from the command line, use this command:

$magick> convert logo: -process analyze -verbose info:Image: logo:
Format: LOGO (ImageMagick Logo)
Class: PseudoClass
Geometry: 640x480
...
filter:brightness:kurtosis: 8.98864
filter:brightness:mean: 238.096
filter:brightness:skewness: -3.04519
filter:brightness:standard-deviation: 46.3286
filter:saturation:kurtosis: 5.9137
filter:saturation:mean: 23.4635
filter:saturation:skewness: 2.71874
filter:saturation:standard-deviation: 64.7734

We provide the Magick Filter Kit to help you get started writing your own custom image filter.