Skip to main content

graphs and networks - Getting cell edges from a picture


I would like to write a program that, given a picture of an epithelium (2D cell array), for example



enter image description here


automatically detects the cell edges and returns the corresponding lattice. Illustratively,


enter image description here


Naturally, if such program is based on contrast and colour detection, the original picture might need to be edited so that cell membrane contrasts enough with cell interior. Furthermore, unlike the above sketch, I would need such polygons to be convex (maybe too tricky?).


Now, I know this might be a lot to ask, so as a first step I would like to know whether there are already inbuilt functions or packages that might help doing this type of image processing (maybe some neural network implementation?). Once edges are obtained as Line-type objects, for example, building the graph or mesh from them shouldn't be that hard.


Just as a reference, I would be interested in building something along the lines of Packing Analyzer.


Edit: Following Lukas Lang's answer below, it seems the presented code doesn't recognise images with "more evident" edges, like the image


enter image description here


or even a similar picture to the first


enter image description here



Image sources: 1, 2 and 3. Might have to do with the way the image is processed via preprocImg or the mergedCells function. Any ideas?



Answer



Here is an approach based on WatershedComponents and MorphologicalGraph. Some of the steps feel a bit over-complicated, so feel free to point out any improvements.


The end result is a Graph expression describing the cell walls:


enter image description here


Here is the code with some intermediate results:


Get the original image:


img = Import["https://i.stack.imgur.com/elbTN.png"]

enter image description here



Do some blurring & sharpening, followed by an extraction of the red color channel. The goal of this step is to get an image with the cell walls as visible as possible.


preprocImg = First@ColorSeparate@Sharpen[#, 5] &@Blur[img, 3]

enter image description here


The next step is the call to WatershedComponents. Unfortunately, I didn't manage to preprocess the image enough to get perfect results, so we have to postprocess them instead.


wsComponents = 
WatershedComponents[preprocImg, Method -> {"MinimumSaliency", .65}];
wsComponents // Colorize

enter image description here



As can be seen, some of the cells are split into multiple pieces. The idea of the next step is to exploit the fact that the cells are all convex. First, we compute the convex hulls of the individual components:


cellMeshes = Map[
ConvexHullMesh@*
Map[{#2, -#} & // Apply](*
convert from image coordinates to plot coordinates *)
]@
Values@GroupBy[First -> Last]@(* group positions by component *)
Catenate@
MapIndexed[List,
wsComponents, {2}](* add position to component indices *);

Show@cellMeshes

enter image description here


We can now merge those that overlap by some amount (I compare to the "reduced area", in analogy to the reduced mass from physics):


mergedCells =
Graph[(* create graph where overlapping cells are connected *)
cellMeshes,
If[(* check whether overlap is big enough *)
Area@RegionIntersection@##*(1/Area@# + 1/Area@#2) > 0.35,
UndirectedEdge@##,

Nothing
] & @@@ Subsets[cellMeshes, {2}](* look at all cell pairs *)
] // Map[RegionUnion]@*
ConnectedComponents(* merge overlapping cells *);
Show@mergedCells

enter image description here


Now we are almost done - we convert the result back into an image, so that we can finally use MorphologicalGraph. For this, we apply some styling to the regions and rasterize:


procImg = Region[(* apply cell styling *)
#,

BaseStyle -> {EdgeForm@{White, Thick}, FaceForm@Black}
] & /@ mergedCells //
Show[#, PlotRangePadding -> 0, ImageMargins -> 0] & //(*
remove image border *)
Rasterize[#, ImageSize -> ImageDimensions@img] & //
Binarize //
ImagePad[ImageCrop@#, BorderDimensions@#] &(* make border black *)

enter image description here


Now we are at the finish line - a call to MorphologicalGraph and some nice presentation is all that's needed now:



MorphologicalGraph[
#,
EdgeStyle -> Directive[Thick, Red],
VertexStyle -> Blue,
VertexSize -> 2,
Prolog -> Inset[img, {0, 0}, {0, 0}, ImageDimensions@img]
] &@procImg

enter image description here


Notes



The key difficulty with this approach is to get preprocImg to be sufficiently "nice" for WatershedComponents to work. For the three images in the question, the following three approaches seem to work:


img = Import["https://i.stack.imgur.com/elbTN.png"]
preprocImg = First@ColorSeparate@Sharpen[#, 5] &@Blur[img, 3]
wsComponents = WatershedComponents[preprocImg, Method -> {"MinimumSaliency", 0.65}];
Row@{img, preprocImg, wsComponents // Colorize}

enter image description here


img = Import["https://i.stack.imgur.com/5RPz5.png"]
preprocImg = ColorNegate@First@ColorSeparate@Sharpen[#, 5] &@Blur[img, 3]
wsComponents = WatershedComponents[preprocImg, Method -> {"MinimumSaliency", 0.65}];

Row@{img, preprocImg, wsComponents // Colorize}

enter image description here


img = Import["https://i.stack.imgur.com/dgz9H.jpg"]
preprocImg =
ColorNegate[20 (#2 - #)*#3] & @@ ColorSeparate@Sharpen[#, 3] &@
Blur[img, 10]
wsComponents = WatershedComponents[preprocImg, Method -> {"MinimumSaliency", 0.45}];

enter image description here




  • As can be seen, each image requires a different approach - unfortunately I couldn't get it to work with a single one yet

  • In the end preprocImg needs to be bright between the cells and dark inside the cells. For the first and second image, this is pretty straightforward using the brightness of the image. (Note that the image needs to be inverted in the second case) For the third image, I had to do some math on the color channels to get a meaningful result.

  • The blur radius is increased in the third case to smooth out the bright and dark areas.

  • The "MinimumSaliency" parameter of WatershedComponents can be used to control the number of cell "candidates" in wscomponents - the best value will depend on the contrast of preprocimg among other things.

  • The components in wscomponents need to resolve the individual cells - in the remaining steps, components are only merged, never split. Too many components on the other hand make the post-processing slow and unreliable (since the overlap criterion doesn't work anymore)


Comments

Popular posts from this blog

list manipulation - Solving word search puzzles

I am trying to create a code that can identify the following terms in a grid of letters: MATHEMATICA, STACK, EXCHANGE and USERS. list1={"M","S","T","A","S","I","S","X","X","T","R","X"}; list2={"A ","T ","H ","X ","R ","X ","G ","R ","S ","H ","X ","A"}; list3={"M","A","T","H","E","M","A","T","I","C","A","I"}; list4={"A","X","S","G","S","X","A","I","R","T","X","T"}; list5={"T","I","T","G","U","C","C","I","R","N",...

calculus and analysis - Integral of the Sinc product

Let us consider the following integral $$ B_n = \int_0^\infty \prod_{k=1,3,5,\dots}^n\frac{\sin (x/k)}{x/k}dx $$ By definition, Sinc[x] == Sin[x]/x , therefore B[n_?OddQ] := Integrate[Product[Sinc[x/k], {k, 1, n, 2}], {x, 0, Infinity}] B /@ Range[1, 13, 2] {Pi/2, Pi/2, Pi/2, Pi/2, Pi/2, Pi/2, Pi/2} OK, everything is fine. But... B[15] 467807924713440738696537864469 Pi/935615849440640907310521750000 What's going on? Answer As Eckhard wrote in comments B[n] is the n-th Borwein integral . (The letter B was not accidental :) ) This funny properties of Borwein integrals is related to the Fourier transform of Sinc function FourierTransform[Sinc[x], x, k] 1/2 Sqrt[Pi/2] (Sign[1 - k] + Sign[1 + k]) Plot[%, {k, -2, 2}, Filling -> 0] which is the box function. The result is $\pi/2$ while the sum $$ 1/3+1/5+\dots+1/n $$ B_n = \frac{\pi}{2} - \pi \bigg(\sum_{k=3,5,\ldots}^n\frac{1}{k} -1\biggr)^\frac{n-1}{2}\prod_{k=3,5,\dots}^n\frac{k}{k-1}. $$ For $n=15$ it is equal to $$ \frac{46780...

implicit - Plotting a function with implicitly defined variable

I have a question about plotting a function with an implicitly defined variable. I think the solution should be something similar like here: Define a function with variables linked implicitly but I quite can't get it to work. I apologize if this has been asked for, I tried doing a thorough search before asking. Anyway, I am trying to plot the following function: $$ u(x,y,t)=\text{sgn}(x+y-t+r(t))\big(e^{-\vert x+y-t+r(t) \vert }-1\big)+r(t)e^{-\vert x+y+r(t)+\ln(\frac{1}{9}r(t)^2-\frac{1}{2}r(t)+1)\vert} $$ where $r(t)$ is implicitly defined with the following equation $$ \ln\vert r(t)\vert-\frac{1}{2}\ln\vert r(t)^2-\frac{9}{2}r(t)+9\vert+\frac{3\sqrt{}{7}}{7}\tan^{-1}\big(\frac{4r(t)-9}{3\sqrt{}{7}}\big)=2t. $$ Ultimately, I would like to use Plot3D for $u(x,y)$ and use Manipulate to see the function at different time steps of $t$. Thank you in advance for your time and help. It's greatly appreciated. Edit: Here is some mathematica format to make life easier: Sign[x + y - t ...