Reputation: 11140
Is there a way to selectively replace colors, based on an arithmetic expression using a pixel's R or G or B value?
Example: say I have an RGB image "foobar.png" and I want to change all pixels whose Red channel is <100 into white.
In pseudocode:
for (all pixels in image) { if (pixel.red < 100) then pixel = 0xffffff; }
Is there a way to pull this off with ImageMagick?
Upvotes: 1
Views: 544
Reputation: 53154
This is similar but slightly different from emcconville's excellent solution. This is in Unix syntax.
#1 compute the 100 out of 255 threshold in percent
#2 read the input
#3 clone the input and make it completely white
#4 clone the input and separate the red channel, threshold and negate so that the white part represents values less than 100 out of 255
#5 use the threshold image as a mask in a composite to select between the original and the white images
#6 write the output
thresh=`convert xc: -format "%[fx:100*100/255]" info:`
convert image.png \
\( -clone 0 -fill white -colorize 100 \) \
\( -clone 0 -channel r -separate +channel -threshold $thresh% -negate \) \
-compose over -composite \
result.png
Upvotes: 3
Reputation: 24439
You can use FX
expressions.
Say I create a test image...
convert -size 400x400 gradient:red-blue input.png
Replace any pixel with a red value < 100 (assuming max-value is a 8bit quantum of 255), can be expressed by..
convert input.png -fx 'r < (100/255) ? #FFFFFF : u' output.png
FX is powerful, but slow. It'll also draw harsh edges. Another approach is to separate the RED channel, convert it to a mask, and composite over the other channels. This can be done with -evaluate-sequance MAX
, or set the alpha channel & compose over a white background.
Create an example input image.
convert -size 400x400 xc:white \
-sparse-color shepards '0 0 red 400 0 blue 400 400 green 0 400 yellow ' \
input.png
convert -size 400x400 xc:white \
\( input.png \
\( +clone -separate -delete 1,2 \
-negate -level 39% -negate \
\) \
-compose CopyOpacity -composite \
\) -compose Atop -composite output.png
Upvotes: 2