In this post, we'll explore the processing operations of Meziantou.Framework.Imaging. This package, under MIT license, allows you to rotate, skew, filter, and recolor images with code written entirely in C#.
An earlier post covered loading, converting, and resizing images. This one is about changing their pixels. Typical use cases are:
- Straightening a scanned page, or a document photographed at an angle
- Sharpening, blurring, or denoising a photo
- Applying a convolution matrix or a color matrix from a paper, an SVG filter, or CSS
- Cleaning up a scan before running an OCR engine on it
- Writing your own filter
#Installation
Shell
dotnet package add Meziantou.Framework.Imaging
The operations are extension methods in the Meziantou.Framework.Imaging namespace. They change the image in place, for every frame of an animation: call Clone first to keep the original.
#Rotating and flipping
Rotate(RotateMode) and Flip move pixels without computing new ones, so they lose nothing:
C#
using var image = Image.Load("photo.png"); // 640x360
image.AutoOrient(); // Apply the EXIF orientation first, so the rotation applies to what viewers show
image.Rotate(RotateMode.Rotate90); // Clockwise
image.Flip(FlipMode.Horizontal);
Console.WriteLine($"{image.Width}x{image.Height}"); // 360x640
Rotate(degrees) turns the image clockwise by any angle, around its center. The image then no longer fills a rectangle, so there are two choices to make: the size of the canvas, and the color of the area the image doesn't cover. By default, the canvas grows to hold the whole image, and the new area is transparent. TransformCanvasMode.Keep keeps the size and cuts the corners:
C#
using var image = Image.Load("photo.png");
using var cut = image.Clone();
image.Rotate(15, new TransformOptions { BackgroundColor = Colors.White });
Console.WriteLine($"{image.Width}x{image.Height}"); // 712x514
cut.Rotate(15, new TransformOptions { BackgroundColor = Colors.White, CanvasMode = TransformCanvasMode.Keep });
Console.WriteLine($"{cut.Width}x{cut.Height}"); // 640x360
An image without alpha channel, such as most JPEG files, cannot store the transparent corners. Instead of making them black, Rotate(15) throws an UnsupportedImageFeatureException, and leaves the image unchanged. Either set an opaque BackgroundColor, or load the image with Image.Load<Rgba32> and save it to a format that supports transparency.
#Skewing and combining transformations
Skew(degreesX, degreesY) slants the image: the first angle leans the vertical lines, and the second one the horizontal lines. It uses the same options as a rotation:
C#
using var image = Image.Load("photo.png");
image.Skew(20, 0, new TransformOptions { BackgroundColor = Colors.White });
Console.WriteLine($"{image.Width}x{image.Height}"); // 772x360
Rotations, skews, scalings, and translations are all affine transformations. To apply several of them, combine them in an AffineTransform and call Transform once. The order matters: Then applies the first transformation, then the next one.
C#
using var image = Image.Load("photo.png");
var transform = AffineTransform.CreateScale(0.5, 0.5)
.Then(AffineTransform.CreateSkew(-20, 0))
.Then(AffineTransform.CreateRotation(45));
image.Transform(transform, new TransformOptions
{
Filter = ResamplingFilter.Lanczos3,
BackgroundColor = Colors.White,
});
Console.WriteLine($"{image.Width}x{image.Height}"); // 400x308
Combining is not only faster. Each call resamples the pixels, and so makes the image a bit softer. I rotated the sample image with 9 small rotations whose sum is 9 degrees, and compared the result with a single rotation of 9 degrees, using the SSIMULACRA 2 metric: 9 calls to Transform score 61, and the 9 rotations combined in one AffineTransform score 100, the score of identical images.
The gray area is TransformOptions.BackgroundColor. Images are scaled down to fit
#Straightening documents
When a page is photographed at an angle, its edges are no longer parallel, and no affine transformation can fix it. CorrectPerspective takes the four corners of the page in the photo, in order around it, and makes them the corners of the image:
C#
using var photo = Image.Load("desk.png");
photo.CorrectPerspective(
topLeft: new PointD(130, 50),
topRight: new PointD(440, 90),
bottomRight: new PointD(510, 520),
bottomLeft: new PointD(40, 440),
size: new Size(420, 560),
options: new TransformOptions { BackgroundColor = Colors.White });
photo.Save("page.png");
The size is optional. Without it, the library uses the lengths of the edges in the photo, which the perspective shortens. If you know the proportions of the page, such as A4, set the size.
A page that is slightly rotated in a scanner is simpler: Deskew finds the angle of the lines of text, rotates the page back, and returns the angle. EstimateSkew only returns the angle:
C#
using var scan = Image.Load("scan.png"); // Rotated by 4 degrees
var angle = scan.Deskew(); // Keeps the size, and fills the uncovered corners with white
Console.WriteLine(angle); // 4

CorrectPerspective needs the corners of the page, Deskew finds the angle by itself
#Convolution matrices
A convolution matrix, or kernel, computes each pixel from its neighbors: multiply each neighbor by the weight at the same position in the matrix, and sum the results. Blurs, sharpening, embossing, and edge detection only differ by their weights. For instance, this matrix sharpens an image:
Take a pixel of value 120 surrounded by pixels of value 100. The new value is 5 * 120 - 4 * 100 = 200: the difference with its neighbors grew from 20 to 100. In a uniform area of value 100, the result is 5 * 100 - 4 * 100 = 100, so nothing changes. That's because the weights add up to 1, which keeps the brightness of the image.
C#
using var image = Image.Load("photo.png");
var sharpen = new ConvolutionKernel(3, 3, [
0, -1, 0,
-1, 5, -1,
0, -1, 0]);
image.Convolve(new ConvolutionOptions(sharpen));
This one is also available as ConvolutionKernel.Sharpen3x3, next to Emboss, SobelX, SobelY, Laplacian3x3, and others. The options handle what the weights cannot:
C#
using var image = Image.Load("photo.png");
// Weights that add up to 25: Divisor brings the sum back to 1
var box = ConvolutionKernel.CreateSeparable([1, 1, 1, 1, 1], [1, 1, 1, 1, 1]);
using var blurred = image.Clone();
blurred.Convolve(new ConvolutionOptions(box) { Divisor = 25 });
// Weights that add up to 0: the result is 0 in uniform areas, and can be negative elsewhere
using var edges = image.Clone();
edges.Convolve(new ConvolutionOptions(ConvolutionKernel.SobelX)
{
PreserveAlpha = true, // Don't filter the alpha channel
Bias = 0.5, // Show 0 as mid-gray, so negative values are visible
});
// Matrices can also be computed
using var moving = image.Clone();
moving.Convolve(new ConvolutionOptions(ConvolutionKernel.CreateMotionBlur(length: 20, degrees: 30)));
A few things to know:
- Alpha: by default, the alpha channel is filtered too. With weights that add up to 0, the alpha becomes 0 and an
Rgba32 image becomes fully transparent. Set PreserveAlpha for these matrices. - Edges: at the border of the image, some neighbors don't exist.
EdgeMode replaces them by the nearest pixel (Clamp, the default), the reflected image (Mirror), the opposite side (Wrap, useful for textures that tile), or transparent black (Zero). - Orientation: the matrix is applied as written, without being flipped. The mathematical convolution flips it, so a matrix that is not symmetric may need to be rotated by 180 degrees if it comes from a source that uses this definition.
- Cost: a 15x15 matrix reads 225 pixels for each pixel. If each weight is the product of a row weight and a column weight, the matrix is separable, and the library filters the rows, then the columns: 30 pixels instead of 225. It detects these matrices by itself, and
IsSeparable tells you the result.
The same operation with different weights
#Blurring, sharpening, and detecting edges
You don't need to write the matrix of the common filters, and some filters are not matrices at all. A median, for instance, sorts the neighbors instead of summing them:
C#
using var image = Image.Load("photo.png");
// Each line is an example: you would use one or two of them
image.GaussianBlur(sigma: 4);
image.MedianBlur(radius: 3); // Removes specks
image.BilateralFilter(radius: 6, spatialSigma: 4, rangeSigma: 0.2); // Smooths the noise, keeps the edges
image.Sharpen(sigma: 2, amount: 1.5, threshold: 0.02); // Unsharp mask
image.RadialBlur(new RadialBlurOptions(RadialBlurKind.Zoom, new PointD(320, 290), amount: 0.2));
image.DetectEdges(EdgeDetector.Sobel); // How strong the edges are
image.DetectCannyEdges(); // Where they are, as thin lines
The bilateral filter blurs the trees, which are close to the color of the mountain behind them, but not the walls of the house
A blur can also be undone, when you know its matrix. WienerDeconvolve restores the details the blur weakened. It is not magic: the details that the blur erased are lost, and the matrix must match the blur.
C#
using var image = Image.Load("shaken.png"); // The camera moved 12 pixels, at 20 degrees
var trail = ConvolutionKernel.CreateMotionBlur(length: 12, degrees: 20);
image.WienerDeconvolve(new WienerDeconvolutionOptions(trail, noiseToSignalRatio: 0.005));
#Changing colors with a matrix
A color matrix works on one pixel at a time: each component of the result is a weighted sum of the red, green, blue, and alpha of the pixel, plus a constant. It has the same layout as the feColorMatrix filter of SVG, and the factories follow the CSS filter functions, so you can port a style from a web page:
C#
using var image = Image.Load("photo.png");
// CSS: filter: saturate(0.6) sepia(0.4) contrast(1.1)
var vintage = ColorMatrix.CreateSaturation(0.6)
.Then(ColorMatrix.CreateSepia(0.4))
.Then(ColorMatrix.CreateContrast(1.1));
image.ApplyColorMatrix(vintage);
// Your own matrix: 4 rows (red, green, blue, alpha of the result)
// of 5 columns (red, green, blue, alpha of the pixel, and a constant)
var swapRedAndBlue = new ColorMatrix([
0, 0, 1, 0, 0,
0, 1, 0, 0, 0,
1, 0, 0, 0, 0,
0, 0, 0, 1, 0]);
image.ApplyColorMatrix(swapRedAndBlue);
As with the affine transformations, Then makes one matrix of several: the colors are computed once, and the intermediate results are neither rounded nor clamped.

Combined is the vintage matrix of the sample
#Cleaning up a scan
Threshold makes an image black and white. By default, it uses one threshold for the whole image, computed with Otsu's method. This is not enough when the lighting is uneven, as a white area in the shadow can be darker than the text in the light. The Sauvola method compares each pixel with the ones around it instead:
C#
using var scan = Image.Load("dark.png");
scan.MedianBlur(1); // Remove the isolated specks
scan.Threshold(new ThresholdOptions { Method = ThresholdMethod.Sauvola, WindowSize = 31 });
Look at the prices in the last image: the median also removed some decimal points
Be careful with the median on small text: a decimal point is barely larger than a speck, and 48.00 becomes 48 00 here. Scan with a higher resolution, or skip this step, when the dots matter.
The morphological filters (Erode, Dilate, MorphologicalOpen, MorphologicalClose, TopHat, and BlackHat) replace each pixel by the darkest or the brightest one of a neighborhood. BlackHat extracts the dark details smaller than the neighborhood, whatever the brightness behind them, so a global threshold works again:
C#
using var scan = Image.Load("dark.png");
scan.Grayscale();
scan.BlackHat(StructuringElement.CreateEllipse(5, 5)); // Larger than the strokes of the text
scan.Threshold(); // White text on black
#Effects and custom filters
Pixelate, OilPaint, Vignette, and Glow are ready to use. When an operation is missing, write it: ApplyRowOperation calls your code for each row of each frame. Here is a solarization, which inverts the bright values:
C#
using var image = Image.Load("photo.png");
image.ApplyRowOperation<Rgba64, SolarizeFilter>(new SolarizeFilter(threshold: 32768));
readonly struct SolarizeFilter(ushort threshold) : IPixelRowOperation<Rgba64>
{
public void Invoke(int y, Span<Rgba64> row)
{
foreach (ref var pixel in row)
{
pixel = new Rgba64(Solarize(pixel.R), Solarize(pixel.G), Solarize(pixel.B), pixel.A);
}
}
private ushort Solarize(ushort value) => value > threshold ? (ushort)(ushort.MaxValue - value) : value;
}
The rows are converted to Rgba64 without loss and back, so the filter works on every integer pixel format. A filter that needs the neighbors of a pixel implements IPixelNeighborhoodOperation, and one that changes the size of the image implements IImageProcessor. If you set MaxDegreeOfParallelism in the configuration of the image, several threads call the row and neighborhood filters at the same time, so they must not change their own state.
Three built-in effects, and the custom filter
#Additional resources
This post is part of the series 'Exploring Meziantou.Framework'. Be sure to check out the rest of the blog posts of the series!Show the 21 posts of the series
Do you have a question or a suggestion about this post? Contact me!