MathGroup Archive 2011

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

Search the Archive

Re: Extracting pixel values from an image under a polygon (region of interest)

  • To: mathgroup at
  • Subject: [mg115337] Re: Extracting pixel values from an image under a polygon (region of interest)
  • From: Patrick Scheibe <pscheibe at>
  • Date: Sat, 8 Jan 2011 03:37:30 -0500 (EST)


a fast, although not pixel-exact, way is to render the polygon as an
image and use this mask to extract you pixels:

img = ImageResize[ExampleData[{"TestImage", "Lena"}], 128];
{nx, ny} = ImageDimensions[img];
poly = Polygon[{{10, 10}, {20, 100}, {120, 40}, {80, 10}}];
Show[Graphics[{Inset[img, {0, 0}, {0, 0}, {nx, ny}], Red, 
   Opacity[0.5], poly}, PlotRange -> {{0, nx}, {0, ny}},
   ImageSize -> {nx, ny}]]
mask = Binarize@
  Image[Graphics[{White, poly}, Background -> Black, 
    ImageSize -> {nx, ny}, PlotRange -> {{0, nx}, {0, ny}}], 
   ColorSpace -> "Grayscale"]
ImageMultiply[img, mask]

You have to take care that the rendered polygon graphics has the same
coordinate system that your image has.
If you only want the (rgb) pixel values which are inside, you can select
them out in various ways. One way is to use Cases:

pixel = Last /@ 
     Flatten[#, 1] & /@ {ImageData[mask, "Bit"], 
       ImageData[img, "Real"]}], {1, rgb_}];
Graphics3D[{RGBColor @@ #, Point[#]} & /@ pixel]

Hope this helps for a start.


On Fri, 2011-01-07 at 04:10 -0500, Mac wrote:
> I've tried solving this general scientific image processing problem
> for some time, alas without success. Given an image and a polygon with
> coordinates describing a region of interest, I would like to extract
> all the image pixels falling completely within the boundaries of the
> polygon (not necessarily a square).
> As an illustrative example consider the following synthetic image +
> region of interest marked in red
> img = Graphics[{Raster[RandomReal[{0, 1}, {10, 10}]], Red,
>    Opacity[0.5], Polygon[{{0.9, 0.9}, {4, 4.1}, {7, 4.1}, {8, 1}}]},
>   Frame -> True]
> I would like to extract all the values of img falling within the
> boundary of the red polygon. The real world problem I face is that I
> have a radar map of the earth's surface with the pixel values
> representing the radar intensity and would like to extract and analyse
> all pixels falling within a specific region (say for instance
> Greenland). Despite the advances in image processing in Mathematica 8
> I still do not see a solution. There is no PixelTake function or
> similar....
> Anway, any help would be much appreciated.
> Mac

  • Prev by Date: Re: Augmenting Mathematica documentation - a serious proposal
  • Next by Date: Re: I'm puzzled by drastic truncation of y-axis in DateListLogPlot
  • Previous by thread: Re: Extracting pixel values from an image under a polygon (region of interest)
  • Next by thread: Solving very large systems of ODEs with NDSolve