588622e2c0fd216d4ffec7a6f65d687784f87a9d
1
module ParasitemiaCore.Morpho
5 open System.Collections.Generic
14 /// Remove M-adjacent pixels. It may be used after thinning.
16 let suppressMAdjacency (img
: Matrix<byte
>) =
21 if img
.[i
, j
] > 0uy && img
.Data.[i
+ 1, j
] > 0uy && (img
.Data.[i
, j
- 1] > 0uy && img
.Data.[i
- 1, j
+ 1] = 0uy || img.Data.[i
, j
+ 1] > 0uy && img.Data.[i
- 1, j
- 1] = 0uy)
26 if img.[i
, j
] > 0uy && img.Data.[i
- 1, j
] > 0uy && (img.Data.[i
, j
- 1] > 0uy && img.Data.[i
+ 1, j
+ 1] = 0uy || img.Data.[i
, j
+ 1] > 0uy && img.Data.[i
+ 1, j
- 1] = 0uy)
34 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
37 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
39 let imgData = img.Data
40 let suppress: bool[,] = Array2D.zeroCreate h w
42 let result = List<List<Point>>()
44 let flood (start: Point) : List<List<Point>> =
45 let sameLevelToCheck = Stack<Point>()
46 let betterLevelToCheck = Stack<Point>()
47 betterLevelToCheck.Push(start)
49 let result' = List<List<Point>>()
51 while betterLevelToCheck.Count > 0 do
52 let p = betterLevelToCheck.Pop()
53 if not
suppress.[p.Y, p.X]
55 suppress.[p.Y, p.X] <- true
56 sameLevelToCheck.Push(p)
57 let current = List<Point>()
59 let mutable betterExists = false
61 while sameLevelToCheck.Count > 0 do
62 let p' = sameLevelToCheck.Pop()
63 let currentLevel = imgData.[p'.Y, p'.X, 0]
64 current.Add(p') |> ignore
68 if ni >= 0 && ni < h && nj >= 0 && nj < w
70 let level = imgData.[ni, nj, 0]
71 let notSuppressed = not
suppress.[ni, nj]
73 if level = currentLevel && notSuppressed
75 suppress.[ni, nj] <- true
76 sameLevelToCheck.Push(Point(nj, ni))
77 elif
if extremumType
= ExtremumType.Maxima then level > currentLevel else level < currentLevel
82 betterLevelToCheck.Push(Point(nj, ni))
91 let maxima = flood (Point(j
, i
))
94 result.AddRange(maxima)
96 result.Select(fun l
-> Points(l
))
98 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
99 findExtremum img ExtremumType.Maxima
101 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
102 findExtremum img ExtremumType.Minima
104 type PriorityQueue () =
106 let q: Points[] = Array.init
size (fun i
-> Points())
107 let mutable highest = -1 // Value of the first elements of 'q'.
108 let mutable lowest = size
110 member this
.NextMax () : byte
* Point =
113 invalidOp
"Queue is empty"
117 l.Remove(next) |> ignore
118 let value = byte
highest
122 highest <- highest - 1
123 while highest > lowest && q.[highest].Count = 0 do
124 highest <- highest - 1
132 member this
.NextMin () : byte
* Point =
135 invalidOp
"Queue is empty"
137 let l = q.[lowest + 1]
139 l.Remove(next) |> ignore
140 let value = byte
(lowest + 1)
145 while lowest < highest && q.[lowest + 1].Count = 0 do
160 member this
.Add (value: byte
) (p: Point) =
170 q.[vi].Add(p) |> ignore
172 member this
.Remove (value: byte
) (p: Point) =
174 if q.[vi].Remove(p) && q.[vi].Count = 0
178 highest <- highest - 1
179 while highest > lowest && q.[highest].Count = 0 do
180 highest <- highest - 1
184 while lowest < highest && q.[lowest + 1].Count = 0 do
187 if highest = lowest // The queue is now empty.
192 member this
.IsEmpty =
195 member this
.Clear () =
196 while highest > lowest do
198 highest <- highest - 1
202 type private AreaState =
207 type private AreaOperation =
212 type private Area (elements
: Points) =
213 member this
.Elements = elements
214 member val Intensity = None with get
, set
215 member val State = AreaState.Unprocessed with get
, set
217 let private areaOperation
(img: Image<Gray, byte
>) (area
: int) (op
: AreaOperation) =
220 let imgData = img.Data
221 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
223 let areas = List<Area>((if op
= AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map
Area)
225 let pixels: Area[,] = Array2D.create
h w null
227 for e
in m
.Elements do
228 pixels.[e
.Y, e
.X] <- m
230 let queue = PriorityQueue()
232 let addEdgeToQueue (elements
: Points) =
237 let p' = Point(nj, ni)
238 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
240 queue.Add (imgData.[ni, nj, 0]) p'
242 // Reverse order is quicker.
243 for i = areas.Count - 1 downto 0 do
245 if m.Elements.Count <= area && m.State <> AreaState.Removed
248 addEdgeToQueue m.Elements
250 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
251 let nextElements = Points()
253 let mutable stop = false
255 let intensity', p = if op
= AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
256 let mutable merged = false
258 if intensity' = intensity // The intensity doesn't
change.
260 if m.Elements.Count + nextElements.Count + 1 > area
262 m.State <- AreaState.Validated
263 m.Intensity <- Some intensity
266 nextElements.Add(p) |> ignore
268 elif
if op
= AreaOperation.Opening then intensity' < intensity else intensity' > intensity
270 m.Elements.UnionWith(nextElements)
271 for e
in nextElements do
272 pixels.[e
.Y, e
.X] <- m
274 if m.Elements.Count = area
276 m.State <- AreaState.Validated
277 m.Intensity <- Some (intensity')
280 intensity <- intensity'
282 nextElements.Add(p) |> ignore
285 match pixels.[p.Y, p.X] with
288 if m'.Elements.Count + m.Elements.Count <= area
290 m'.State <- AreaState.Removed
291 for e in m'.Elements do
292 pixels.[e
.Y, e
.X] <- m
293 queue.Remove imgData.[e
.Y, e
.X, 0] e
294 addEdgeToQueue m'.Elements
295 m.Elements.UnionWith(m'.Elements)
296 let intensityMax = if op
= AreaOperation.Opening then queue.Max else queue.Min
297 if intensityMax <> intensity
299 intensity <- intensityMax
305 m.State <- AreaState.Validated
306 m.Intensity <- Some (intensity)
309 if not stop && not merged
314 let p' = Point(nj, ni)
315 if ni < 0 || ni >= h || nj < 0 || nj >= w
317 m.State <- AreaState.Validated
318 m.Intensity <- Some (intensity)
320 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
322 queue.Add (imgData.[ni, nj, 0]) p'
326 if m.Elements.Count + nextElements.Count <= area
328 m.State <- AreaState.Validated
329 m.Intensity <- Some intensity'
330 m.Elements.UnionWith(nextElements)
334 if m.State = AreaState.Validated
336 match m.Intensity with
338 for p in m.Elements do
339 imgData.[p.Y, p.X, 0] <- i
344 /// Area opening on byte image.
346 let areaOpen (img: Image<Gray, byte>) (area: int) =
347 areaOperation img area AreaOperation.Opening
350 /// Area closing on byte image.
352 let areaClose (img: Image<Gray, byte>) (area: int) =
353 areaOperation img area AreaOperation.Closing
355 // A simpler algorithm than 'areaOpen' on byte image but slower.
356 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
359 let imgData = img.Data
360 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
362 let histogram = Array.zeroCreate 256
363 for i = 0 to h - 1 do
364 for j = 0 to w - 1 do
365 let v = imgData.[i, j, 0] |> int
366 histogram.[v] <- histogram.[v] + 1
368 let flooded : bool[,] = Array2D.zeroCreate h w
370 let pointsChecked = HashSet<Point>()
371 let pointsToCheck = Stack<Point>()
373 for level = 255 downto 0 do
374 let mutable n = histogram.[level]
377 for i = 0 to h - 1 do
378 for j = 0 to w - 1 do
379 if not flooded.[i, j] && imgData.[i, j, 0] = byte level
381 let mutable maxNeighborValue = 0uy
382 pointsChecked.Clear()
383 pointsToCheck.Clear()
384 pointsToCheck.Push(Point(j, i))
386 while pointsToCheck.Count > 0 do
387 let next = pointsToCheck.Pop()
388 pointsChecked.Add(next) |> ignore
389 flooded.[next.Y, next.X] <- true
392 let p = Point(next.X + nx, next.Y + ny)
393 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
395 let v = imgData.[p.Y, p.X, 0]
398 if not (pointsChecked.Contains(p))
400 pointsToCheck.Push(p)
401 elif v > maxNeighborValue
403 maxNeighborValue <- v
405 if int maxNeighborValue < level && pointsChecked.Count <= area
407 for p in pointsChecked do
408 imgData.[p.Y, p.X, 0] <- maxNeighborValue
411 type Island (cmp: IComparer<float32>) =
412 member val Shore = Heap.Heap<float32, Point>(cmp) with get
413 member val Level = 0.f with get, set
414 member val Surface = 0 with get, set
415 member this.IsInfinite = this.Surface = Int32.MaxValue
417 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: ('a -> float32 -> unit) option) (op: AreaOperation) =
421 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
423 let comparer = if op = AreaOperation.Opening
424 then { new IComparer<float32> with member this.Compare(v1, v2) = v1.CompareTo(v2) }
425 else { new IComparer<float32> with member this.Compare(v1, v2) = v2.CompareTo(v1) }
427 let ownership: Island[,] = Array2D.create h w null
429 // Initialize islands with their shore.
430 let islands = List<Island>()
431 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
435 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
437 let shorePoints = Points()
439 ownership.[p.Y, p.X] <- island
443 let neighbor = Point(nj, ni)
444 if ni >= 0 && ni < h && nj >= 0 && nj < w && Object.ReferenceEquals(ownership.[ni, nj], null) && not (shorePoints.Contains(neighbor))
446 shorePoints.Add(neighbor) |> ignore
447 island.Shore.Add earth.[ni, nj, 0] neighbor
449 for area, obj in areas do
450 for island in islands do
451 let mutable stop = island.Shore.IsEmpty
453 // 'true' if 'p' is owned or adjacent to 'island'.
454 let inline ownedOrAdjacent (p: Point) : bool =
455 ownership.[p.Y, p.X] = island ||
456 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
457 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
458 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
459 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
461 while not stop && island.Surface < area do
462 let level, next = island.Shore.Max
463 let other = ownership.[next.Y, next.X]
464 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
466 island.Shore.RemoveNext ()
468 if not <| Object.ReferenceEquals(other, null)
469 then // We touching another island.
470 if island.IsInfinite || other.IsInfinite || island.Surface + other.Surface >= area || comparer.Compare(island.Level, other.Level) < 0
473 else // We can merge 'other' into 'surface
'.
474 island.Surface <- island.Surface + other.Surface
475 island.Level <- other.Level
476 // island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then other.Level else island.Level
477 for l, p in other.Shore do
478 let mutable currentY = p.Y + 1
479 while currentY < h && ownership.[currentY, p.X] = other do
480 ownership.[currentY, p.X] <- island
481 currentY <- currentY + 1
485 elif comparer.Compare(level, island.Level) > 0
489 island.Shore.RemoveNext ()
493 if ni < 0 || ni >= h || nj < 0 || nj >= w
495 island.Surface <- Int32.MaxValue
498 let neighbor = Point(nj, ni)
499 if not <| ownedOrAdjacent neighbor
501 island.Shore.Add earth.[ni, nj, 0] neighbor
504 ownership.[next.Y, next.X] <- island
505 island.Level <- level
506 island.Surface <- island.Surface + 1
508 let mutable diff = 0.f
510 for i = 0 to h - 1 do
511 for j = 0 to w - 1 do
512 match ownership.[i, j] with
516 diff <- diff + l - earth.[i, j, 0]
520 | Some f' -> f
' obj diff
525 /// Area opening on float image.
527 let areaOpenF (img: Image<Gray, float32>) (area: int) =
528 areaOperationF img [ area, () ] None AreaOperation.Opening
531 /// Area closing on float image.
533 let areaCloseF (img: Image<Gray, float32>) (area: int) =
534 areaOperationF img [ area, () ] None AreaOperation.Closing
537 /// Area closing on float image with different areas. Given areas must be sorted increasingly.
538 /// For each area the function 'f
' is called with the associated area value of type 'a
and the
volume difference
539 /// Between the previous and the current closing.
541 let areaOpenFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
542 areaOperationF
img areas (Some f) AreaOperation.Opening
545 /// Same as 'areaOpenFWithFun' for closing operation.
547 let areaCloseFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
548 areaOperationF
img areas (Some f) AreaOperation.Closing
551 /// Zhang and Suen thinning algorithm.
552 /// Modify 'mat' in place.
554 let thin (mat
: Matrix<byte
>) =
557 let mutable data1 = mat
.Data
558 let mutable data2 = Array2D.copy
data1
560 let mutable pixelChanged = true
561 let mutable oddIteration = true
563 while pixelChanged do
564 pixelChanged <- false
565 for i
= 0 to h - 1 do
566 for j
= 0 to w - 1 do
567 if data1.[i
, j
] = 1uy
569 let p2 = if i
= 0 then 0uy else data1.[i
-1, j
]
570 let p3 = if i
= 0 || j = w-1 then 0uy else data1.[i
-1, j+1]
571 let p4 = if j = w-1 then 0uy else data1.[i
, j+1]
572 let p5 = if i
= h-1 || j = w-1 then 0uy else data1.[i
+1, j+1]
573 let p6 = if i
= h-1 then 0uy else data1.[i
+1, j]
574 let p7 = if i
= h-1 || j = 0 then 0uy else data1.[i
+1, j-1]
575 let p8 = if j = 0 then 0uy else data1.[i
, j-1]
576 let p9 = if i
= 0 || j = 0 then 0uy else data1.[i
-1, j-1]
578 let sumNeighbors = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
579 if sumNeighbors >= 2uy && sumNeighbors <= 6uy &&
580 (if p2 = 0uy && p3 = 1uy then 1 else 0) +
581 (if p3 = 0uy && p4 = 1uy then 1 else 0) +
582 (if p4 = 0uy && p5 = 1uy then 1 else 0) +
583 (if p5 = 0uy && p6 = 1uy then 1 else 0) +
584 (if p6 = 0uy && p7 = 1uy then 1 else 0) +
585 (if p7 = 0uy && p8 = 1uy then 1 else 0) +
586 (if p8 = 0uy && p9 = 1uy then 1 else 0) +
587 (if p9 = 0uy && p2 = 1uy then 1 else 0) = 1 &&
589 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
590 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
597 oddIteration <- not oddIteration
603 /// Remove all 8-connected pixels with an area equal or greater than 'areaSize'.
604 /// Modify 'mat' in place.
606 let removeArea (mat
: Matrix<byte
>) (areaSize
: int) =
617 use mat' = new Matrix<byte>(mat.Size)
623 let data' = mat'.Data
625 for i
= 0 to h - 1 do
626 for j = 0 to w - 1 do
627 if data'.[i, j] = 1uy
629 let neighborhood = List<Point>()
630 let neighborsToCheck = Stack<Point>()
631 neighborsToCheck.Push(Point(j, i))
634 while neighborsToCheck.Count > 0 do
635 let n = neighborsToCheck.Pop()
637 for (ni, nj) in neighbors do
640 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
642 neighborsToCheck.Push(Point(pj, pi))
643 data'.[pi, pj] <- 0uy
644 if neighborhood.Count <= areaSize
646 for n in neighborhood do
647 data.[n.Y, n.X] <- 0uy
649 let connectedComponents (img: Image<Gray, byte
>) (startPoints
: List<Point>) : Points =
653 let pointChecked = Points()
654 let pointToCheck = Stack<Point>(startPoints
);
658 while pointToCheck.Count > 0 do
659 let next = pointToCheck.Pop()
660 pointChecked.Add(next) |> ignore
663 if ny
<> 0 && nx
<> 0
665 let p = Point(next.X + nx
, next.Y + ny
)
666 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)