How do I convert a Color Image to Black and White using ImageMagick?

Viewed 1409

Background: I performed an Indexed conversion in Gimp of a color image and the result was a nice B&W version of the source Image.

I have tried numerous options in ImageMagick to no avail. I can get close but never quite as clear and crisp as what gimp seems to do effortlessly.

Here is my source:

var bmp = new MagickImage(sourceImage);

bmp.Threshold(new ImageMagick.Percentage(60));

bmp.Resample(200, 200);
bmp.ColorType = ColorType.Bilevel;
bmp.BitDepth(1);
bmp.Settings.Compression = CompressionMethod.Group4;
bmp.Strip();

bmp.Format = MagickFormat.Tiff;

I have been adjusting the Threshold call and have tried various suggestions I have seen online with varying amounts of success.

magickimage has a feature called -monochrome but I have not found how that is achieved in the .net library.

I am sure this is possible but what is the best way to achieve a nice B&W conversion.

sample image

2 Answers

With ImageMagick 7, you can do Otsu thresholding.

Input:

enter image description here

magick check.png -alpha off -auto-threshold otsu x.png

Result:

enter image description here

There is no built-in equivalent in ImageMagick 6. However I have a script, otsuthresh that will do that At my web site

So in ImageMagick 6, you just have to do simple thresholding.

convert check.png -alpha off -threshold 50% y.png

Result:

enter image description here

I note that your input image has an opaque alpha channel which needs to be removed to get proper results.

This is possibly the simplest way you can use Greyscale in Magick.NET.

MagickImage image = new MagickImage(imagePath);
image.Grayscale();

string fileName = image.FileName + "_grey.png";
image.Write(fileName);

Instead of image.FileName you can also directly use the image path if you have it. Optionally you can add a PixelIntensityMethod in Greyscale for eventually better results.

Don't forget to call image.RePage() when you want to crop the image.

Related