Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

At the white regions of this image I want to add a few random arrows. I would like to realize two different of adding the random arrows:

  • The arrows may not leave the white region
  • The arrows have to leave the white region


 img = Import["ExampleData/spikey2.png"]

enter image description here

How can you do this with Mathematica?

In particular I would like to know how to detect the white regions, and how to store this information. If I give you an arrow can you tell me whether it crosses non-white parts of the image?

There is not much space for the arrows in this picture. It would be good to add a bit of white canvas to create some space for the arrows.

share|improve this question
How about showing what you tried, and more importantly, what you expect to actually see. – bill s Apr 10 '13 at 19:28
I made a mistake in may question. I said I the arrows have to leave the white region, but in fact they should not. I corrected this. Sorry for that – sjdh Apr 11 '13 at 6:00
@bills I don't how to find the white regions in an image. So I don't know where to start. – sjdh Apr 11 '13 at 6:01

Extending s0rce with ImageValuePosition (new in 9.0).

Module[{w, h},
 {w, h} = ImageDimensions@img;
    Arrowheads[.08], Opacity[.7],
    Map[Arrow[{#, # - .5 (# - .5 {w, h})}] &,
     RandomSample[ImageValuePositions[img, {1, 1, 1}], 20]]},
   AspectRatio -> Automatic,
   ImageSize -> {w, h},
   PlotRange -> {{0, w}, {0, h}}]]


Arrows end half way to center.

share|improve this answer

Here is one way:

img = Import["ExampleData/spikey2.png"];
arrowstarts = RandomChoice[ImageValuePositions[img, {1, 1, 1}], 10]
arrowends = RandomChoice[ImageValuePositions[img, {0, 0, 0}, 0.75], 10]
arrows = Graphics[
   MapThread[Arrow[{#1, #2}] &, {arrowstarts, arrowends}], 
   AspectRatio -> Automatic, ImageSize -> {150, 135}, 
   Background -> Transparent, PlotRange -> {{0, 150}, {0, 135}}];
ImageCompose[img, arrows]


share|improve this answer
Isn't your graphics missing PlotRange? Graphics without it displays max and min values and nothing further, which makes the composition a bit off, doesn't it. – BoLe Apr 10 '13 at 20:40
@BoLe, um it appears to work, I just ran my code again on a fresh kernel and it worked. – s0rce Apr 10 '13 at 21:48
It works, it composes the images but not correctly. To see this change 10 to 1 in both RandomChoice and run a few times if necessary. – BoLe Apr 10 '13 at 21:57
@BoLe, you're right! fixed with ImageValuePositions and PlotRange. – s0rce Apr 10 '13 at 23:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.