Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all except one colour from an image (commandline or code)

I would like to extract a single colour (e.g. #a87830) from an image, changing every other colour to white. The input can be a bit noisy, so adjacent pixels of a close colour could be included. Ideally all non-white pixels at the end would be converted to black (i.e. output is a 1-bit-depth image).

I might want to batch process this, so I am hoping for something like an imagemagick commandline, or something I could code up using the PHP imagemagick extension. (I am sure ImageMagick must be able to do this, if the right parameters can just be worked out, which is why I tagged it, but I am open to other software, as long as it works on Linux.)

Background: I am trying to do the first preprocessing stage for the ContourTrace program, which is nicely shown by this image:

enter image description here

like image 388
Darren Cook Avatar asked Apr 20 '15 07:04

Darren Cook


2 Answers

Not sure if this is sophisticated enough for you. Convert all pixels similar, within 30% of your stated colour, to black and then make the rest white.

convert in.png -fuzz 30% -fill black -opaque "#a87830" -threshold 10% out.png

enter image description here

You can "add in" more tones that you would like to become black by adding further -opaque commands, like this

convert in.jpg -fuzz 20% -fill black  \
    -opaque "#a87830"                 \
    -opaque "#a6725f"                 \
    -threshold 1% out.png

which may allow you to decrease the fuzz and thereby remove other tones you don't want.

like image 120
Mark Setchell Avatar answered Sep 30 '22 18:09

Mark Setchell


Here is one to try:

convert                              \
  http://i.stack.imgur.com/rK259.png \
 -fuzz 33%                           \
 -fill black                         \
 -opaque "#A87830"                   \
 -threshold 12%                      \
  black+white.png

The -fuzz parameter makes all colors match that are within a certain proximity of the color defined by -opaque. No -fuzz, and you'll match these pixels only which are exactly "#A87830".

The -threshold converts color pixels to black or white, where the percentage defines the limit: above turns black, below turns white.

black+white.png

You can modify the command from -opaque "<color-definition>" to +opaque "<color-definition>" to invert the meaning of the color selection: it will replace pixels that are NOT this color (this time I skip the -threshold parameter in order to keep colors):

convert                              \
  http://i.stack.imgur.com/rK259.png \
 -fuzz 33%                           \
 -fill black                         \
 +opaque "#FFFFFF"                   \
  other.png

other.png

like image 36
Kurt Pfeifle Avatar answered Sep 30 '22 17:09

Kurt Pfeifle