Search code examples
imagemagick

How do I change white pixels to black if they are surrounded by black pixels?


The zoomed-in image below shows part of a black-and-white scan of a text document. Notice that there are some unwanted white pixels within the black letters. Is there a way to use ImageMagick to remove white pixels that are completely surrounded by black pixels?

Scanned letters


Solution

  • Use a median filter. A median filter sets a pixel to the median value of its neighbors (so in case of black and white, to the most frequent). So a white pixel among black pixels turns black and disappears.

    convert input_image -median 3 output_image
    

    enter image description here

    As you see above the big speckle near the edge in the n won't let go to easily since part of the background is also included in the median sample.

    Using -median 6 makes it disappear but this may have other impacts in your image (rounding of shapes for instance):

    enter image description here

    For very small spots there is also a -despeckle operator.