1

Topic: Smooth binary image

This script will smooth a binary (pure black/white) image. It is done by toggling a pixel value if it has more neighbors of the opposite color than of its own color.

using MeeSoft.ImageProcessing;

public class ScriptOp : MeeSoft.ImageProcessing.Operations.ScriptOperation.Base
{
    const int Iterations = 2;
    
    const float BlackThreshold = 0.5f;
    
    protected override void ApplyToPlane(BitmapPlane srcPlane, BitmapPlane dstPlane, int planeIndex)
    {
        for (int i=0; i<Iterations; i++)
        {
            if (i>0)
                srcPlane = new BitmapPlane(dstPlane);
            base.ApplyToPlane(srcPlane, dstPlane, planeIndex);    
        }
    }

    protected override float GetPixel(int x, int y, int p, BitmapPlane source)
    {
        // Count number of black pixels surrounding (x,y)
        int blackCount = 0;
        for (int dy=-1; dy<=1; dy++)
            for (int dx=-1; dx<=1; dx++)
                if ((dx != 0 || dy != 0) && source.GetPixelSafe(x+dx, y+dy) < BlackThreshold)
                    blackCount++;
                    
        if (source[x,y] < BlackThreshold) // Pixel is black
        {
            if (blackCount < 4)
                return 1;
            else
                return 0;
        }
        else // Pixel is white
        {
            if (blackCount > 4)
                return 0;
            else
                return 1;
        }            
    }
}
Michael Vinther

> software developer <