Page 1 of 1

How to swap colors in an image?

Posted: 2018-03-11T07:52:41-07:00
by TheMasterGabriel
Is there a way to swap the colors of an image? For example, in the image below the white can become the red and the red can become the white. I need the anti-aliasing around the edge of the circle to swap as well.

The circle is just an example. I'm asking more generically, so I can apply the same commands to any image of 2 main colors (and anti-alisasing between them).

Image

Re: How to swap colors in an image?

Posted: 2018-03-11T08:47:46-07:00
by snibgo
I can't think of an easy way to do this. A hard way is:

1. Get the two most common colours.

2. Convert those with "-level-colors" to black and white, and from there to the original colours in the opposite order.

This should work, including anti-aliasing, but it needs two commands in a script.

Re: How to swap colors in an image?

Posted: 2018-03-11T11:03:51-07:00
by TheMasterGabriel
Oh wow "-level-colors" is what I was looking for!
I already knew the 2 main colors, so it was as simple as running:

Code: Select all

convert test.png -level-colors "#73233C",white +level-colors white,"#73233C" test_swapped.png
Is there a way to preserve transparent pixels in the image?

Re: How to swap colors in an image?

Posted: 2018-03-11T18:13:39-07:00
by snibgo
What version IM? "level-colors" doesn't change transparency, for me, using IM v6. For v7, we need to restrict the operations to RGB channels, with "-channel RGB" before the operations and "+channel" after.

Code: Select all

magick test.png -channel RGB -level-colors "#73233C",white +level-colors white,"#73233C" +channel test_swapped.png