Automate your color correction with a Perl script

Card Trick

© articular, Fotolia

© articular, Fotolia


If you have grown tired of manually correcting color-casted images (as described in last month's Perl column), you might appreciate a script that automates this procedure.

Last month, I wrote about using reference cards to correct the white balance in digital photos by taking a test snapshot (see Figure 1) [2]. The black, white, and gray plastic cards, which are available from any good photography equipment dealer, should not generate any color values in a digital image. This provides three calibration points for low, medium, and high light intensity, which the GIMP photo editing tool can then reference to correct your snapshots.

Figure 1: Discovering the color values for the three cards in the picture – the script reads the RGB values along the horizontal line at the center to obtain the graph in
Figure 2: The values in the unfiltered image fluctuate too strongly to identify the cards reliably.

Perl Magic

How can a simple Perl script find out which pixel values the three cards create, even though their position in the image is not known, without using artificial intelligence?

If the photographer manages to spread the cards in the center of the image as shown in Figure 1, the script can follow an imaginary horizontal line and identify the cards on the basis of pixel values along the x axis.

The light intensity measured along this line remains constant for a fairly substantial distance, as long as the line lies within one reference card.

Once the line touches the background, the pixel values will start to fluctuate significantly.

Listing 1, graphdraw, uses the CPAN Imager module to create the graphs shown in Figure 2.

The graphs represent the red, green, and blue components of the color values along the horizontal line drawn in Figure 1 on a coordinate system in which the x axis matches the x coordinates in the image and the y value represents the color component value with a range of 0 through 255.

The CPAN Imager module's read() (line 12) is a multi-talented beast that can identify, read, and convert any popular image format to its own internal Imager format for editing.

Listing 1




If something goes wrong, the Imager methods return false values. For more details about an error, cautious programmers tend to call the errstr() method to return a cleartext description of the issue. The getpixel() method (line 30) examines the RGB values of a pixel in the image at a location defined by its x and y coordinates and returns an Imager::Color object, which contains the pixel's RGB values.

A call to rgba() (line 35) returns these values along with the value for the alpha channel. Here, you are just interested in the first three RGB values.

The script calls shift in line 41 to extract them one by one.

Image View

The Imager::Plot module represents boring numbers as graphs in an attractive coordinate system without too much hassle with respect to scaling, axis labeling, or graphical layout, and it returns image files in all popular formats, allowing the user to check them later with an image viewer or web browser. The new() constructor (line 45) accepts the dimensions for the resulting image and the path to an installed True Type font, which it then uses for axis labeling.

The script collects the required coordinates in a hash of hashes, to which $data points. It stores all the x coordinates in $data->{x} and all red values in $data->{red}; the green and blue values are stored in the same manner. The AddDataSet() method (line 55) then adds the data separately for each of the three graphs, each of which are drawn in a different color.

On completion, a new Imager object is created in line 71; later, it will create the resulting graphics file. Before this happens, the box() method colors the image background white, then Render() draws the coordinate system, the labels, and the three graphs in one fell swoop.

Finally, the write() method saves the output file on disk in PNG format.

Nicely Out of Focus

Before a script can reliably identify the three areas at the center of the image, you need to make some preparations. Figure 2 clearly shows how much the graph fluctuates, and this is obviously going to make it difficult to identify the somewhat flatter areas. Thus, the cardfind detection script (Listing 2) needs to run a blur filter that uses the "Gaussian Blur" method with a radius of 10 to defocus the image (lines 15ff.).

In an out-of-focus image (see Figure 3), the color transitions between individual pixels are less abrupt. Instead of jumping directly from a white to black pixel, an out-of-focus image will show a transition with several gray scale values. The graph shown in Figure 4, which represents the pixel values on the same horizontal line, is far smoother as a result of this, and also simplifies the task of identifying the three areas to be identified.

Figure 3: Setting the blur filter to "Gaussian Blur" with a radius of 10 pixels defocuses the image and smoothes the pixel values.
Figure 4: The image, defocused with the blur filter, has smoother graphs, making it easier to identify the flat spots caused by the three cards.

Listing 2



Back to School?

In these card areas, the curve is fairly flat over a length of hundreds of pixels. If you remember your math from school, you might recall that the first derivative of a graph like this at flat spots is constant and about zero, whereas the values will be far higher and fluctuate significantly everywhere else.

Figure 5 shows the first derivative of intensity values, which are calculated by adding the pixel values for the red, green, and blue channels. The recorded values are indicative of the fluctuation of the original graph and drop to zero over quite considerable distances.

Figure 5: The first derivative of the intensity graph tends toward zero for homogeneous sections of the image.

The cards, with their homogeneous gray scales, occupy these positions in the original image. Thus, the script just needs to follow this graph, create a ring buffer of about 50 investigated values, and alert when the buffer average drops to a value close to zero. When it does so, it has located a card.

Return to Search

When the buffer values start to fluctuate again, the script has left the card area and returns to the state "search for the next homogeneous location." The script should be able to find all three regions you are looking for and return the RGB values it finds there in YAML format. This lets the picfix script I discussed in last month's Perl column adjust the white balance of other images with the same light conditions.

And Repeat

The photographer still needs to repeat the reference card shot whenever the scene changes. All following photos of the same scene can then be corrected by GIMP and the picfix script.

To make sure this approach works even if the snapshot happens to have a fairly homogeneous background, lines 66 through 68 not only check to see whether the mean value in the buffer is less than 3, but also whether the algorithm is in the middle third of the image, ignoring the left and right thirds.

The script uses normal Perl arrays as ring buffers and uses push() to append new values before checking to see whether the array exceeds the maximum length of the buffer. If this is the case, it deletes the first array element by calling shift(). This shortens the array by one element, and the second element moves up to the first spot.

To calculate the first derivative of the fairly complex pixel function, you can use a simplified numeric approach.

The ring buffer, @intens_ring, stores the intensity values of the last 50 pixels, which were created by adding the red, green, and blue values at the processed x coordinates.

To extract the three values from the four-element list returned by the rgba() method (line 36), the script relies on the array slice technique @components[0,1,2] (line 41). The value of the first derivate – that is, the slope of the graph at this point – is then approximated as the difference between the first and last elements in the ring buffer at constant distance x. Positive or negative slopes are of no interest, so abs() converts them to positive values if needed.

To find out whether the algorithm is currently in one of the flat parts of the graph that are being investigated, or in a more mountainous region, the script sets up a second ring buffer, @diff_ring, which contains the last 50 values determined for the first derivate of the graph (lines 51, 52). The avg() function defined in line 107ff. calculates the mean value of 50 intensity values. If the algorithm is currently in a peaky region, a mean value below a threshold of 3 is all you need to identify a flat part.

Once the script hits a flat area, it takes a mean increase of more than 10 to convince the state machine that it is back in the mountains.

Each time the script identifies a flat area, line 72 stores the RGB values of the first pixel found in this area in the @ctl_points array. Because you are only interested in three flat spots; the last instruction in line 101 scraps any others.


Finally, the Dump() function from the YAML module from CPAN outputs the results (Figure 6) in the form of a YAML file, sample.yml.

Figure 6: The cardfind script accepts the name of an image file, autonomously performs various calculations, and outputs YAML-formatted color values to reflect the values measured for the reference cards.
Figure 7: Using color values read from the reference cards, the picfix script willadapt the red channel, using 16/16, 123/129, and 189/191 as referencepoints.

Storing the results and passing them in to last month's picfix script as -c sample.yml lets you correct the color casting in the image with the cards, and any number of images you took with the same lighting – but don't forget to hold the cards in the middle of the photo to make sure that the simple algorithm finds them. To find the cards otherwise, you would need a far more sophisticated algorithm.

On the other hand, Perl, with its treasure of modules on CPAN, gives you ample fodder for your experiments.


  1. Listings for this article:
  2. "Color Play" by Michael Schilli, Linux Magazine, September 2008:

The Author

Michael Schilli works as a Software Developer at Yahoo!, Sunnyvale, California. He wrote "Perl Power" for Addison-Wesley and can be contacted at His homepage is at