Skip to main content

Changing color of an object in an image


Consider the following image:


Red ball in a non-red environment


How can I change all red colors in this image into (for example) blue.



Answer



Here's a version using Manipulate with a Locator to pick the colour to replace. There is also a tolerance control which determines how wide a range of hues to replace.


i=Import["http://i.stack.imgur.com/Qr7Tx.jpg"];

{h,s,b}=ColorSeparate[i,"HSB"];


colourchange[c_,from_,tol_,to_]:=Module[
{offset=Mod[c-from+0.5,1]-0.5},
If[Abs[offset]>tol,c,to]];

Manipulate[
ColorCombine[
{ImageApply[colourchange[#,ImageValue[h,pos],tol,ColorConvert[to,Hue][[1]]]&,h],s,b},
"HSB"],
{{to,Blue,"Change to"},Blue},

{{tol,-0.01,"Tolerance"},-0.01,0.5},
{{pos,{100,50}},Locator}]

enter image description here


Comments