Services & Resources / Wolfram Forums / MathGroup Archive

MathGroup Archive 2012

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How to change individual colors of an image

  • To: mathgroup at
  • Subject: [mg125079] Re: How to change individual colors of an image
  • From: Szabolcs Horvát <szhorvat at>
  • Date: Mon, 20 Feb 2012 02:53:42 -0500 (EST)
  • Delivered-to:
  • References: <jho1tn$5r0$>

On 2/18/2012 1:26 PM, Alexei Boulbitch wrote:
> Dear community,
> My question relates to the work with an image. There are plenty of operators influencing the image as a whole. May be I have missed, but I could not find, if it is possible to work with all pixels possessing a given colour, (or may be, a group of colours close to one another) in  such  a way that this colour changes to another that is desired one.
> To be precise, below I paste a full form of a small piece of an image with white (or light gray), black and red fragments. Is it possible to say, change black into blue? Light gray into yellow?
> To see the image please copy-paste the 30 lists given below along with two code lines (combining them into the image) into Mathematica and execute:

Dear Alexei,

A simple way to send complex expressions is using Compress/Uncompress 
(see at the end of this message).

There are several ways to achieve what you need, but I am going to show 
a more general way here, called masking.  This can be generalized to 
many problems.

Suppose the image is stored in variable img

Let's first find all pixels that have colour {138, 138, 138}/255

mask = Binarize[img, # == {138, 138, 138}/255 &]

Alternatively use colours that are close to this shade of grey:

mask = Binarize[img, Norm[# - {138, 138, 138}/255] < 0.05 &]

Then change the image in the matching region green (i.e. colour {0,1,0}:

ImageApply[{0, 1, 0} &, img, Masking -> mask]

If you have Mathematica 7, you could use ImageApply directly:

ImageApply[If[# == {138, 138, 138}/255, {0, 1, 0}, #] &, img]


This is the image in a more compact and ASCII-only format:

img = Uncompress@


This is how it was generated:

wrap[string_, width_] :=
   Riffle[Partition[Characters[string], width, width, {1, 1}, {}],

wrap[Compress[img], 60]

Szabolcs Horvát
Visit Mathematica.SE:

  • Prev by Date: Re: How best to implement a hash table in Mathematica
  • Next by Date: Re: Iterative solution to a transcendental equation.
  • Previous by thread: How to change individual colors of an image
  • Next by thread: Interrupt a block