How to swap colors in an image?

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
TheMasterGabriel
Posts: 2
Joined: 2018-03-11T07:41:33-07:00
Authentication code: 1152

How to swap colors in an image?

Post 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
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: How to swap colors in an image?

Post 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.
snibgo's IM pages: im.snibgo.com
TheMasterGabriel
Posts: 2
Joined: 2018-03-11T07:41:33-07:00
Authentication code: 1152

Re: How to swap colors in an image?

Post 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?
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: How to swap colors in an image?

Post 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
snibgo's IM pages: im.snibgo.com
Post Reply