# Transform an image into a region and compute on it

**URL:** <https://community.wolfram.com/t/transform-an-image-into-a-region-and-compute-on-it/3429>\
**Category:** Ideas\
**Tags:** equation-solving, geometry, graphics-and-visualization, numerical-computation\
**Created:** [September 25, 2014, 6:50pm UTC](https://community.wolfram.com/t/transform-an-image-into-a-region-and-compute-on-it/3429 "2014-09-25T18:50:52Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Vitaliyk](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/vitaliyk/32/45591_2.png) [@Vitaliyk](https://community.wolfram.com/u/Vitaliyk)\
**Post date:** [September 25, 2014, 6:50pm UTC](https://community.wolfram.com/t/transform-an-image-into-a-region-and-compute-on-it/3429/1 "2014-09-25T18:50:52Z")

</div>

Imagine you have an irregular image like this:

 ![sdfgewr456.png](https://global.discourse-cdn.com/wolfram/original/3X/5/c/5c127d7627bd47fc11aaa9e7744de825c1f2b1a3.png)

How would you solve a differential equation or compute an integral over a region of this shape?

First, let’s get the boundary:

```
i = Import["http://wolfr.am/ZS7ERg"];
edge = EdgeDetect[ColorNegate[i]]

```

 ![sdfgghr678596454.png](https://global.discourse-cdn.com/wolfram/original/3X/5/4/54922fa8a7904c533f05a6c3dd1472c85a3dfe39.png)

It is now easy to extract points with `Position` but how to order them inside `Polygon` correctly along the boundary? Using `FindShortestTour`! - a trick I learned from this excellent post: [Find polygons corresponding to image borders](https://wolfram.discourse.group/t/1953/1)

```
reg = MeshRegion[#, Polygon[Last[FindShortestTour[#]]]] &@ Position[ImageData[edge], 1]

```

 ![sdfs4563gndfgert.png](https://global.discourse-cdn.com/wolfram/original/3X/5/1/512440fbe2ec8c45728bb8e11448e396697d90e5.png)

Now we are ready to have fun:

```
Plot3D[Cos[.0002 ((x - 215)^2 + (y - 215)^2)]^2, {x, y} \[Element] reg, 
Mesh -> None, Filling -> -3, FillingStyle -> Red, PlotRange -> All, BoxRatios -> {1, 1, 1/3}]

```

 ![asdas2343254678656fdgsdas.png](https://global.discourse-cdn.com/wolfram/original/2X/a/a218aa07cd0b0a9cc0ad0a4e59b73110b3b538c8.png)

```
uif = NDSolveValue[{\!\(\*SubsuperscriptBox[\(\[Del]\), \({x, y}\), \(2\)]\(u[x, y]\)\) == 0, 
    DirichletCondition[u[x, y] == 1/2 + Sin[.0001 x y] , True]}, u, {x, y} \[Element] reg];

ContourPlot[uif[x, y], {x, y} \[Element] reg, PlotPoints -> 50, 
 ContourStyle -> Opacity[.2], Contours -> 50, ColorFunction -> "Rainbow"]

```

 ![345dfg54tgdfg456tdsf.jpg](https://global.discourse-cdn.com/wolfram/original/2X/0/00fd807f37f0dbf22e401732216af0ec0a6d72d4.jpeg)

---

<div class="post-metadata">

**Author:** ![arnoudb](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/arnoudb/32/41177_2.png) [@arnoudb](https://community.wolfram.com/u/arnoudb)\
**Post date:** [September 25, 2014, 7:44pm UTC](https://community.wolfram.com/t/transform-an-image-into-a-region-and-compute-on-it/3429/2 "2014-09-25T19:44:15Z")

</div>

This is very cool, thanks for sharing!

Here is a variation to transform a (black and white) image to a graphics expression, while taking into account multiple regions.

Throughout this post I will use the following test image:

```
image = Import["c:\\Users\\arnoudb.WRI\\paw.png"]

```

 ![paw1.png](https://global.discourse-cdn.com/wolfram/original/2X/1/1ea35103e0abc621da8a58e5ee54c488d481cab9.png)

This is a helper function which uses MorphologicalComponents to split the image up into a list of images, each containing a single coherent part of the original image:

```
ImageToParts[image_] := Module[{components, max},
 components = MorphologicalComponents[Binarize@ColorNegate[image]];
 max = Max[Union[Flatten[components]]];
 parts = Table[Image[components /. Table[i -> If[i == j, 1, 0], {i, max}]], {j, max}]
]

```

And here is an example of what it does (the third image is a tiny speck in the original):

```
ImageToParts[image]

```

 ![paw2.png](https://global.discourse-cdn.com/wolfram/original/3X/3/4/34f18828fec3e3ef708ed715a6542f0ecb5776b8.png)

This function uses the helper function to split up the original image and find the ‘shortest tour’ for the edge points of each sub-image:

```
ImageToGraphics[image_] := Module[
 {dims, parts, edges, points, shortest, smooth, prims},
 dims = ImageDimensions[image];
 parts = ImageToParts[image];
 prims = Table[
  edges = EdgeDetect[part];
  points = {Last[#], 1+Last[dims] - First[#]} & /@ N@Position[ImageData[edges], 1];
  shortest = FindShortestTour[points][[2]];
  smooth = Mean /@ Partition[points[[shortest]], 8, 1, {-1, 1}];
  Polygon[smooth],
  {part, parts}];
 Graphics[
 {EdgeForm[Black], Opacity[.5], Red, prims},
 ImageSize -> dims,
 PlotRange -> {{1, First[#]}, {1, Last[#]}} &[dims]
 ]
]

```

And here is the result, when calling it on the test image:

```
graphics = ImageToGraphics[image]

```

 ![paw3.png](https://global.discourse-cdn.com/wolfram/original/3X/d/1/d1990d12eca5c3e9b984f162b90730aa30168df6.png)

And this shows how the test image and the graphics expression match:

```
Overlay[{image, graphics}]

```

 ![paw5.png](https://global.discourse-cdn.com/wolfram/original/3X/c/1/c17fa2c893e5b949382f2e5f9d1596815f223d1c.png)

---

<div class="post-metadata">

**Author:** ![carlson](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/carlson/32/6475_2.png) [@carlson](https://community.wolfram.com/u/carlson)\
**Post date:** [September 25, 2014, 8:07pm UTC](https://community.wolfram.com/t/transform-an-image-into-a-region-and-compute-on-it/3429/3 "2014-09-25T20:07:30Z")

</div>

Here’s a related challenge: how can I extract the line segments in this image as Line objects?

```
Show[PolyhedronData["Spikey"], Boxed -> False, Lighting -> {White}]

```

 ![Spikey.png](https://global.discourse-cdn.com/wolfram/original/3X/e/4/e4ff1eb78da88813e7d65246c0010181da506b3b.png)

---

<div class="post-metadata">

**Author:** ![Vitaliyk](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/vitaliyk/32/45591_2.png) [@Vitaliyk](https://community.wolfram.com/u/Vitaliyk)\
**Post date:** [September 25, 2014, 8:37pm UTC](https://community.wolfram.com/t/transform-an-image-into-a-region-and-compute-on-it/3429/4 "2014-09-25T20:37:00Z")

</div>

I think this is not perfect but could be improved:

```
i = Rasterize[Show[PolyhedronData["Spikey"], Boxed -> False, Lighting -> {White},ImageSize -> 1500]];

g = i // ColorNegate // Binarize // MorphologicalGraph;

Graphics[GraphicsComplex[
  Sort[Transpose[{VertexList[g], GraphEmbedding[g]}]][[All, 2]], 
  Line[EdgeList[g] /. UndirectedEdge -> List]]]

```

 ![asdasdas23234867543fsds.png](https://global.discourse-cdn.com/wolfram/original/3X/e/8/e8e0407f0f0d0f3275ecdebd60ff91701fa8c5fe.png)

---

<div class="post-metadata">

**Author:** ![carlson](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/carlson/32/6475_2.png) [@carlson](https://community.wolfram.com/u/carlson)\
**Post date:** [September 25, 2014, 8:43pm UTC](https://community.wolfram.com/t/transform-an-image-into-a-region-and-compute-on-it/3429/5 "2014-09-25T20:43:57Z")

</div>

Not perfect, but darned good! Thanks, Vitaliy!

Chris

---

<div class="post-metadata">

**Author:** ![Vitaliyk](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/vitaliyk/32/45591_2.png) [@Vitaliyk](https://community.wolfram.com/u/Vitaliyk)\
**Post date:** [September 29, 2014, 3:45pm UTC](https://community.wolfram.com/t/transform-an-image-into-a-region-and-compute-on-it/3429/6 "2014-09-29T15:45:27Z")

</div>

In the “Neat Examples” section of documentation for ToElementMesh there is another way to do this. Follow the _[LINK](http://reference.wolfram.com/language/FEMDocumentation/ref/ToElementMesh.html#1467926226)_.

 ![O_172.gif](https://global.discourse-cdn.com/wolfram/original/3X/8/c/8ce9d7417bff616edd49abd36a4403a80f342d20.gif)
