1
module ParasitemiaCore.ImgTools
5 open System.Collections.Generic
16 // Normalize image values between 0uy and 255uy.
17 let normalizeAndConvert (img
: Image<Gray, 'TDepth>) : Image<Gray, byte> =
18 let min = ref [| 0.0 |]
19 let minLocation = ref <| [| Point() |]
20 let max = ref [| 0.0 |]
21 let maxLocation = ref <| [| Point() |]
22 img.MinMax(min, max, minLocation, maxLocation)
23 ((img.Convert<Gray, float32>() - (!min).[0]) / ((!max).[0] - (!min).[0]) * 255.0).Convert<Gray, byte>()
25 let saveImg (img: Image<'TColor, 'TDepth>) (filepath: string) =
28 let saveMat (mat: Matrix<'TDepth>) (filepath
: string) =
29 use img = new Image<Gray, 'TDeph>(mat.Size)
33 type Histogram = { data: int[]; total: int; sum: int; min: float32; max: float32 }
35 let histogramImg (img: Image<Gray, float32>) (nbSamples: int) : Histogram =
36 let imgData = img.Data
39 let min = ref [| 0.0 |]
40 let minLocation = ref <| [| Point() |]
41 let max = ref [| 0.0 |]
42 let maxLocation = ref <| [| Point() |]
43 img.MinMax(min, max, minLocation, maxLocation)
44 float32 (!min).[0], float32 (!max).[0]
46 let inline bin (x: float32) : int =
47 let p = int ((x - min) / (max - min) * float32 nbSamples)
48 if p >= nbSamples then nbSamples - 1 else p
50 let data = Array.zeroCreate nbSamples
52 for i in 0 .. img.Height - 1 do
53 for j in 0 .. img.Width - 1 do
54 let p = bin imgData.[i, j, 0]
55 data.[p] <- data.[p] + 1
57 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
59 let histogramMat (mat: Matrix<float32>) (nbSamples: int) : Histogram =
60 let matData = mat.Data
64 let minLocation = ref <| Point()
66 let maxLocation = ref <| Point()
67 mat.MinMax(min, max, minLocation, maxLocation)
68 float32 !min, float32 !max
70 let inline bin (x: float32) : int =
71 let p = int ((x - min) / (max - min) * float32 nbSamples)
72 if p >= nbSamples then nbSamples - 1 else p
74 let data = Array.zeroCreate nbSamples
76 for i in 0 .. mat.Height - 1 do
77 for j in 0 .. mat.Width - 1 do
78 let p = bin matData.[i, j]
79 data.[p] <- data.[p] + 1
81 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
83 let histogram (values: float32 seq) (nbSamples: int) : Histogram =
84 let mutable min = Single.MaxValue
85 let mutable max = Single.MinValue
90 if v < min then min <- v
91 if v > max then max <- v
93 let inline bin (x: float32) : int =
94 let p = int ((x - min) / (max - min) * float32 nbSamples)
95 if p >= nbSamples then nbSamples - 1 else p
97 let data = Array.zeroCreate nbSamples
101 data.[p] <- data.[p] + 1
103 { data = data; total = n; sum = Array.sum data; min = min; max = max }
105 let otsu (hist: Histogram) : float32 * float32 * float32 =
108 let mutable maximum = 0.0
109 let mutable level = 0
110 let sum = hist.data |> Array.mapi (fun i v -> i * v) |> Array.sum |> float
112 for i in 0 .. hist.data.Length - 1 do
113 wB <- wB + hist.data.[i]
116 let wF = hist.total - wB
119 sumB <- sumB + i * hist.data.[i]
120 let mB = (float sumB) / (float wB)
121 let mF = (sum - float sumB) / (float wF)
122 let between = (float wB) * (float wF) * (mB - mF) ** 2.;
123 if between >= maximum
131 for i in 0 .. level - 1 do
132 sum <- sum + i * hist.data.[i]
133 nb <- nb + hist.data.[i]
134 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
139 for i in level + 1 .. hist.data.Length - 1 do
140 sum <- sum + i * hist.data.[i]
141 nb <- nb + hist.data.[i]
142 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
145 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
147 toFloat level, toFloat mean1, toFloat mean2
150 /// Remove M-adjacent pixels. It may be used after thinning.
152 let suppressMAdjacency (img: Matrix<byte>) =
155 for i in 1 .. h - 2 do
156 for j in 1 .. w - 2 do
157 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)
160 for i in 1 .. h - 2 do
161 for j in 1 .. w - 2 do
162 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)
167 /// Find edges of an image by using the Canny approach.
168 /// The thresholds are automatically defined with otsu on gradient magnitudes.
170 /// <param name="img"></param>
171 let findEdges (img: Image<Gray, float32>) : Matrix<byte> * Image<Gray, float32> * Image<Gray, float32> =
176 new ConvolutionKernelF(array2D [[ 1.0f; 0.0f; -1.0f ]
177 [ 2.0f; 0.0f; -2.0f ]
178 [ 1.0f; 0.0f; -1.0f ]], Point(1, 1))
180 let xGradient = img.Convolution(sobelKernel)
181 let yGradient = img.Convolution(sobelKernel.Transpose())
183 let xGradientData = xGradient.Data
184 let yGradientData = yGradient.Data
185 for r in 0 .. h - 1 do
186 xGradientData.[r, 0, 0] <- 0.f
187 xGradientData.[r, w - 1, 0] <- 0.f
188 yGradientData.[r, 0, 0] <- 0.f
189 yGradientData.[r, w - 1, 0] <- 0.f
191 for c in 0 .. w - 1 do
192 xGradientData.[0, c, 0] <- 0.f
193 xGradientData.[h - 1, c, 0] <- 0.f
194 yGradientData.[0, c, 0] <- 0.f
195 yGradientData.[h - 1, c, 0] <- 0.f
197 use magnitudes = new Matrix<float32>(xGradient.Size)
198 use angles = new Matrix<float32>(xGradient.Size)
199 CvInvoke.CartToPolar(xGradient, yGradient, magnitudes, angles) // Compute the magnitudes and angles.
201 let thresholdHigh, thresholdLow =
202 let sensibilityHigh = 0.1f
203 let sensibilityLow = 0.0f
204 let threshold, _, _ = otsu (histogramMat magnitudes 300)
205 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
207 // Non-maximum suppression.
208 use nms = new Matrix<byte>(xGradient.Size)
210 let nmsData = nms.Data
211 let anglesData = angles.Data
212 let magnitudesData = magnitudes.Data
213 let xGradientData = xGradient.Data
214 let yGradientData = yGradient.Data
216 for i in 0 .. h - 1 do
217 nmsData.[i, 0] <- 0uy
218 nmsData.[i, w - 1] <- 0uy
220 for j in 0 .. w - 1 do
221 nmsData.[0, j] <- 0uy
222 nmsData.[h - 1, j] <- 0uy
224 for i in 1 .. h - 2 do
225 for j in 1 .. w - 2 do
226 let vx = xGradientData.[i, j, 0]
227 let vy = yGradientData.[i, j, 0]
228 if vx <> 0.f || vy <> 0.f
230 let angle = anglesData.[i, j]
232 let vx', vy' = abs vx, abs vy
233 let ratio2 = if vx' > vy' then vy' / vx' else vx' / vy'
234 let ratio1 = 1.f - ratio2
236 let mNeigbors (sign: int) : float32 =
238 then ratio1 * magnitudesData.[i, j + sign] + ratio2 * magnitudesData.[i + sign, j + sign]
239 elif angle < PI / 2.f
240 then ratio2 * magnitudesData.[i + sign, j + sign] + ratio1 * magnitudesData.[i + sign, j]
241 elif angle < 3.f * PI / 4.f
242 then ratio1 * magnitudesData.[i + sign, j] + ratio2 * magnitudesData.[i + sign, j - sign]
244 then ratio2 * magnitudesData.[i + sign, j - sign] + ratio1 * magnitudesData.[i, j - sign]
245 elif angle < 5.f * PI / 4.f
246 then ratio1 * magnitudesData.[i, j - sign] + ratio2 * magnitudesData.[i - sign, j - sign]
247 elif angle < 3.f * PI / 2.f
248 then ratio2 * magnitudesData.[i - sign, j - sign] + ratio1 * magnitudesData.[i - sign, j]
249 elif angle < 7.f * PI / 4.f
250 then ratio1 * magnitudesData.[i - sign, j] + ratio2 * magnitudesData.[i - sign, j + sign]
251 else ratio2 * magnitudesData.[i - sign, j + sign] + ratio1 * magnitudesData.[i, j + sign]
253 let m = magnitudesData.[i, j]
254 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
256 nmsData.[i, j] <- 1uy
258 // suppressMConnections nms // It's
not helpful
for the rest of the process (ellipse
detection).
260 let edges = new Matrix<byte
>(xGradient.Size)
261 let edgesData = edges.Data
263 // Hysteresis thresholding.
264 let toVisit = Stack<Point>()
265 for i
in 0 .. h - 1 do
266 for j
in 0 .. w - 1 do
267 if nmsData.[i
, j
] = 1uy && magnitudesData.[i
, j
] >= thresholdHigh
269 nmsData.[i
, j
] <- 0uy
270 toVisit.Push(Point(j
, i
))
271 while toVisit.Count > 0 do
272 let p = toVisit.Pop()
273 edgesData.[p.Y, p.X] <- 1uy
276 if i
' <> 0 || j' <> 0
280 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
282 nmsData.[ni, nj] <- 0uy
283 toVisit.Push(Point(nj, ni))
285 edges, xGradient, yGradient
287 let gaussianFilter (img : Image<'TColor, 'TDepth>) (standardDeviation
: float) : Image<'TColor, 'TDepth> =
288 let size = 2 * int (ceil
(4.0 * standardDeviation
)) + 1
289 img.SmoothGaussian(size, size, standardDeviation
, standardDeviation
)
291 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
293 img.Data.[p.Y, p.X, 0] <- intensity
299 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
302 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
304 let imgData = img.Data
305 let suppress: bool[,] = Array2D.zeroCreate h w
307 let result = List<List<Point>>()
309 let flood (start: Point) : List<List<Point>> =
310 let sameLevelToCheck = Stack<Point>()
311 let betterLevelToCheck = Stack<Point>()
312 betterLevelToCheck.Push(start)
314 let result' = List<List<Point>>()
316 while betterLevelToCheck.Count > 0 do
317 let p = betterLevelToCheck.Pop()
318 if not suppress.[p.Y, p.X]
320 suppress.[p.Y, p.X] <- true
321 sameLevelToCheck.Push(p)
322 let current = List<Point>()
324 let mutable betterExists = false
326 while sameLevelToCheck.Count > 0 do
327 let p' = sameLevelToCheck.Pop()
328 let currentLevel = imgData.[p'.Y, p'.X, 0]
329 current.Add(p') |> ignore
333 if ni >= 0 && ni < h && nj >= 0 && nj < w
335 let level = imgData.[ni, nj, 0]
336 let notSuppressed = not suppress.[ni, nj]
338 if level = currentLevel && notSuppressed
340 suppress.[ni, nj] <- true
341 sameLevelToCheck.Push(Point(nj, ni))
342 elif
if extremumType
= ExtremumType.Maxima then level > currentLevel else level < currentLevel
347 betterLevelToCheck.Push(Point(nj, ni))
354 for i
in 0 .. h - 1 do
355 for j in 0 .. w - 1 do
356 let maxima = flood (Point(j, i
))
359 result.AddRange(maxima)
361 result.Select(fun l
-> Points(l
))
363 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
364 findExtremum img ExtremumType.Maxima
366 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
367 findExtremum img ExtremumType.Minima
369 type PriorityQueue () =
371 let q: Points[] = Array.init
size (fun i
-> Points())
372 let mutable highest = -1 // Value of the first elements of 'q'.
373 let mutable lowest = size
375 member this
.NextMax () : byte
* Point =
378 invalidOp
"Queue is empty"
382 l.Remove(next) |> ignore
383 let value = byte
highest
387 highest <- highest - 1
388 while highest > lowest && q.[highest].Count = 0 do
389 highest <- highest - 1
397 member this
.NextMin () : byte
* Point =
400 invalidOp
"Queue is empty"
402 let l = q.[lowest + 1]
404 l.Remove(next) |> ignore
405 let value = byte
(lowest + 1)
410 while lowest < highest && q.[lowest + 1].Count = 0 do
425 member this
.Add (value: byte
) (p: Point) =
435 q.[vi].Add(p) |> ignore
437 member this
.Remove (value: byte
) (p: Point) =
439 if q.[vi].Remove(p) && q.[vi].Count = 0
443 highest <- highest - 1
444 while highest > lowest && q.[highest].Count = 0 do
445 highest <- highest - 1
449 while lowest < highest && q.[lowest + 1].Count = 0 do
452 if highest = lowest // The queue is now empty.
457 member this
.IsEmpty =
460 member this
.Clear () =
461 while highest > lowest do
463 highest <- highest - 1
467 type private AreaState =
472 type private AreaOperation =
477 type private Area (elements
: Points) =
478 member this
.Elements = elements
479 member val Intensity = None with get
, set
480 member val State = AreaState.Unprocessed with get
, set
482 let private areaOperation
(img: Image<Gray, byte
>) (area
: int) (op
: AreaOperation) =
485 let imgData = img.Data
486 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
488 let areas = List<Area>((if op
= AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map
Area)
490 let pixels: Area[,] = Array2D.create
h w null
492 for e
in m.Elements do
493 pixels.[e
.Y, e
.X] <- m
495 let queue = PriorityQueue()
497 let addEdgeToQueue (elements
: Points) =
502 let p' = Point(nj, ni)
503 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
505 queue.Add (imgData.[ni, nj, 0]) p'
507 // Reverse order is quicker.
508 for i in areas.Count - 1 .. -1 .. 0 do
510 if m.Elements.Count <= area && m.State <> AreaState.Removed
513 addEdgeToQueue m.Elements
515 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
516 let nextElements = Points()
518 let mutable stop = false
520 let intensity', p = if op
= AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
521 let mutable merged = false
523 if intensity' = intensity // The intensity doesn't
change.
525 if m.Elements.Count + nextElements.Count + 1 > area
527 m.State <- AreaState.Validated
528 m.Intensity <- Some intensity
531 nextElements.Add(p) |> ignore
533 elif
if op
= AreaOperation.Opening then intensity' < intensity else intensity' > intensity
535 m.Elements.UnionWith(nextElements)
536 for e
in nextElements do
537 pixels.[e
.Y, e
.X] <- m
539 if m.Elements.Count = area
541 m.State <- AreaState.Validated
542 m.Intensity <- Some (intensity')
545 intensity <- intensity'
547 nextElements.Add(p) |> ignore
550 match pixels.[p.Y, p.X] with
553 if m'.Elements.Count + m.Elements.Count <= area
555 m'.State <- AreaState.Removed
556 for e in m'.Elements do
557 pixels.[e
.Y, e
.X] <- m
558 queue.Remove imgData.[e
.Y, e
.X, 0] e
559 addEdgeToQueue m'.Elements
560 m.Elements.UnionWith(m'.Elements)
561 let intensityMax = if op
= AreaOperation.Opening then queue.Max else queue.Min
562 if intensityMax <> intensity
564 intensity <- intensityMax
570 m.State <- AreaState.Validated
571 m.Intensity <- Some (intensity)
574 if not stop && not merged
579 let p' = Point(nj, ni)
580 if ni < 0 || ni >= h || nj < 0 || nj >= w
582 m.State <- AreaState.Validated
583 m.Intensity <- Some (intensity)
585 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
587 queue.Add (imgData.[ni, nj, 0]) p'
591 if m.Elements.Count + nextElements.Count <= area
593 m.State <- AreaState.Validated
594 m.Intensity <- Some intensity'
595 m.Elements.UnionWith(nextElements)
599 if m.State = AreaState.Validated
601 match m.Intensity with
603 for p in m.Elements do
604 imgData.[p.Y, p.X, 0] <- i
609 /// Area opening on byte image.
611 let areaOpen (img: Image<Gray, byte>) (area: int) =
612 areaOperation img area AreaOperation.Opening
615 /// Area closing on byte image.
617 let areaClose (img: Image<Gray, byte>) (area: int) =
618 areaOperation img area AreaOperation.Closing
620 // A simpler algorithm than 'areaOpen' on byte image but slower.
621 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
624 let imgData = img.Data
625 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
627 let histogram = Array.zeroCreate 256
628 for i in 0 .. h - 1 do
629 for j in 0 .. w - 1 do
630 let v = imgData.[i, j, 0] |> int
631 histogram.[v] <- histogram.[v] + 1
633 let flooded : bool[,] = Array2D.zeroCreate h w
635 let pointsChecked = HashSet<Point>()
636 let pointsToCheck = Stack<Point>()
638 for level in 255 .. -1 .. 0 do
639 let mutable n = histogram.[level]
642 for i in 0 .. h - 1 do
643 for j in 0 .. w - 1 do
644 if not flooded.[i, j] && imgData.[i, j, 0] = byte level
646 let mutable maxNeighborValue = 0uy
647 pointsChecked.Clear()
648 pointsToCheck.Clear()
649 pointsToCheck.Push(Point(j, i))
651 while pointsToCheck.Count > 0 do
652 let next = pointsToCheck.Pop()
653 pointsChecked.Add(next) |> ignore
654 flooded.[next.Y, next.X] <- true
657 let p = Point(next.X + nx, next.Y + ny)
658 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
660 let v = imgData.[p.Y, p.X, 0]
663 if not (pointsChecked.Contains(p))
665 pointsToCheck.Push(p)
666 elif v > maxNeighborValue
668 maxNeighborValue <- v
670 if int maxNeighborValue < level && pointsChecked.Count <= area
672 for p in pointsChecked do
673 imgData.[p.Y, p.X, 0] <- maxNeighborValue
676 type Island (cmp: IComparer<float32>) =
677 member val Shore = Heap.Heap<float32, Point>(cmp) with get
678 member val Level = 0.f with get, set
679 member val Surface = 0 with get, set
680 member this.IsInfinite = this.Surface = Int32.MaxValue
682 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: ('a -> float32 -> unit) option) (op: AreaOperation) =
686 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
688 let comparer = if op = AreaOperation.Opening
689 then { new IComparer<float32> with member this.Compare(v1, v2) = v1.CompareTo(v2) }
690 else { new IComparer<float32> with member this.Compare(v1, v2) = v2.CompareTo(v1) }
692 let ownership: Island[,] = Array2D.create h w null
694 // Initialize islands with their shore.
695 let islands = List<Island>()
696 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
700 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
702 let shorePoints = Points()
704 ownership.[p.Y, p.X] <- island
708 let neighbor = Point(nj, ni)
709 if ni >= 0 && ni < h && nj >= 0 && nj < w && Object.ReferenceEquals(ownership.[ni, nj], null) && not (shorePoints.Contains(neighbor))
711 shorePoints.Add(neighbor) |> ignore
712 island.Shore.Add earth.[ni, nj, 0] neighbor
714 for area, obj in areas do
715 for island in islands do
716 let mutable stop = island.Shore.IsEmpty
718 // 'true' if 'p' is owned or adjacent to 'island'.
719 let inline ownedOrAdjacent (p: Point) : bool =
720 ownership.[p.Y, p.X] = island ||
721 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
722 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
723 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
724 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
726 while not stop && island.Surface < area do
727 let level, next = island.Shore.Max
728 let other = ownership.[next.Y, next.X]
729 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
731 island.Shore.RemoveNext ()
733 if not <| Object.ReferenceEquals(other, null)
734 then // We touching another island.
735 if island.IsInfinite || other.IsInfinite || island.Surface + other.Surface >= area
738 else // We can merge 'other' into 'surface
'.
739 island.Surface <- island.Surface + other.Surface
740 island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then island.Level else other.Level
741 for l, p in other.Shore do
742 let mutable currentY = p.Y + 1
743 while currentY < h && ownership.[currentY, p.X] = other do
744 ownership.[currentY, p.X] <- island
745 currentY <- currentY + 1
749 elif comparer.Compare(level, island.Level) > 0
753 island.Shore.RemoveNext ()
757 if ni < 0 || ni >= h || nj < 0 || nj >= w
759 island.Surface <- Int32.MaxValue
762 let neighbor = Point(nj, ni)
763 if not <| ownedOrAdjacent neighbor
765 island.Shore.Add earth.[ni, nj, 0] neighbor
768 ownership.[next.Y, next.X] <- island
769 island.Level <- level
770 island.Surface <- island.Surface + 1
772 let mutable diff = 0.f
774 for i in 0 .. h - 1 do
775 for j in 0 .. w - 1 do
776 match ownership.[i, j] with
780 diff <- diff + l - earth.[i, j, 0]
784 | Some f' -> f
' obj diff
789 /// Area opening on float image.
791 let areaOpenF (img: Image<Gray, float32>) (area: int) =
792 areaOperationF img [ area, () ] None AreaOperation.Opening
795 /// Area closing on float image.
797 let areaCloseF (img: Image<Gray, float32>) (area: int) =
798 areaOperationF img [ area, () ] None AreaOperation.Closing
801 /// Area closing on float image with different areas. Given areas must be sorted increasingly.
802 /// For each area the function 'f
' is called with the associated area value of type 'a
and the volume difference
803 /// Between the previous and the current closing.
805 let areaOpenFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
806 areaOperationF
img areas (Some f) AreaOperation.Opening
809 /// Same as 'areaOpenFWithFun' for closing operation.
811 let areaCloseFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
812 areaOperationF
img areas (Some f) AreaOperation.Closing
815 /// Zhang and Suen thinning algorithm.
816 /// Modify 'mat' in place.
818 let thin (mat
: Matrix<byte
>) =
821 let mutable data1 = mat
.Data
822 let mutable data2 = Array2D.copy
data1
824 let mutable pixelChanged = true
825 let mutable oddIteration = true
827 while pixelChanged do
828 pixelChanged <- false
831 if data1.[i
, j] = 1uy
833 let p2 = if i
= 0 then 0uy else data1.[i
-1, j]
834 let p3 = if i
= 0 || j = w-1 then 0uy else data1.[i
-1, j+1]
835 let p4 = if j = w-1 then 0uy else data1.[i
, j+1]
836 let p5 = if i
= h-1 || j = w-1 then 0uy else data1.[i
+1, j+1]
837 let p6 = if i
= h-1 then 0uy else data1.[i
+1, j]
838 let p7 = if i
= h-1 || j = 0 then 0uy else data1.[i
+1, j-1]
839 let p8 = if j = 0 then 0uy else data1.[i
, j-1]
840 let p9 = if i
= 0 || j = 0 then 0uy else data1.[i
-1, j-1]
842 let sumNeighbors = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
843 if sumNeighbors >= 2uy && sumNeighbors <= 6uy &&
844 (if p2 = 0uy && p3 = 1uy then 1 else 0) +
845 (if p3 = 0uy && p4 = 1uy then 1 else 0) +
846 (if p4 = 0uy && p5 = 1uy then 1 else 0) +
847 (if p5 = 0uy && p6 = 1uy then 1 else 0) +
848 (if p6 = 0uy && p7 = 1uy then 1 else 0) +
849 (if p7 = 0uy && p8 = 1uy then 1 else 0) +
850 (if p8 = 0uy && p9 = 1uy then 1 else 0) +
851 (if p9 = 0uy && p2 = 1uy then 1 else 0) = 1 &&
853 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
854 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
861 oddIteration <- not oddIteration
867 /// Remove all 8-connected pixels with an area equal or greater than 'areaSize'.
868 /// Modify 'mat' in place.
870 let removeArea (mat
: Matrix<byte
>) (areaSize
: int) =
881 use mat' = new Matrix<byte>(mat.Size)
887 let data' = mat'.Data
891 if data'.[i, j] = 1uy
893 let neighborhood = List<Point>()
894 let neighborsToCheck = Stack<Point>()
895 neighborsToCheck.Push(Point(j, i))
898 while neighborsToCheck.Count > 0 do
899 let n = neighborsToCheck.Pop()
901 for (ni, nj) in neighbors do
904 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
906 neighborsToCheck.Push(Point(pj, pi))
907 data'.[pi, pj] <- 0uy
908 if neighborhood.Count <= areaSize
910 for n in neighborhood do
911 data.[n.Y, n.X] <- 0uy
913 let connectedComponents (img: Image<Gray, byte
>) (startPoints
: List<Point>) : Points =
917 let pointChecked = Points()
918 let pointToCheck = Stack<Point>(startPoints
);
922 while pointToCheck.Count > 0 do
923 let next = pointToCheck.Pop()
924 pointChecked.Add(next) |> ignore
927 if ny
<> 0 && nx
<> 0
929 let p = Point(next.X + nx
, next.Y + ny
)
930 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)
936 let drawLine (img: Image<'TColor, 'TDepth>) (color
: 'TColor) (x0: int) (y0: int) (x1: int) (y1: int) (thickness: int) =
937 img.Draw(LineSegment2D(Point(x0, y0), Point(x1, y1)), color, thickness);
939 let drawLineF (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0
: float) (y0
: float) (x1
: float) (y1
: float) (thickness
: int) =
940 img.Draw(LineSegment2DF(PointF(float32 x0
, float32 y0
), PointF(float32 x1
, float32 y1
)), color
, thickness
, CvEnum.LineType.AntiAlias);
942 let drawEllipse (img: Image<'TColor, 'TDepth>) (e
: Ellipse) (color
: 'TColor) (alpha: float) =
945 img.Draw(Emgu.CV.Structure.Ellipse(PointF(float32 e.Cx, float32 e.Cy), SizeF(2.f * e.B, 2.f * e.A), e.Alpha / PI * 180.f), color, 1, CvEnum.LineType.AntiAlias)
947 let windowPosX = e.Cx - e.A - 5.f
948 let gapX = windowPosX - (float32 (int windowPosX))
950 let windowPosY = e.Cy - e.A - 5.f
951 let gapY = windowPosY - (float32 (int windowPosY))
953 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e.A + 5.f) |> int, 2.f * (e.A + 5.f) |> int)
956 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
958 use i = new Image<'TColor, 'TDepth>(img.ROI.Size)
959 i.Draw(Emgu.CV.Structure.Ellipse(PointF(float32 <| (e.A + 5.f + gapX) , float32 <| (e.A + 5.f + gapY)), SizeF(2.f * e.B, 2.f * e.A), e.Alpha / PI * 180.f), color, 1, CvEnum.LineType.AntiAlias)
960 CvInvoke.AddWeighted(img, 1.0, i, alpha, 0.0, img)
961 img.ROI <- Rectangle.Empty
963 let drawEllipses (img: Image<'TColor, 'TDepth>) (ellipses: Ellipse list) (color: 'TColor) (alpha
: float) =
964 List.iter
(fun e
-> drawEllipse img e
color alpha
) ellipses
966 let rngCell = System.Random()
967 let drawCell (img: Image<Bgr, byte
>) (drawCellContent
: bool) (c
: Cell) =
970 let colorB = rngCell.Next(20, 70)
971 let colorG = rngCell.Next(20, 70)
972 let colorR = rngCell.Next(20, 70)
974 for y
in 0 .. c
.elements
.Height - 1 do
975 for x
in 0 .. c
.elements
.Width - 1 do
976 if c
.elements
.[y
, x
] > 0uy
978 let dx, dy
= c
.center
.X - c
.elements
.Width / 2, c
.center
.Y - c
.elements
.Height / 2
979 let b = img.Data.[y
+ dy
, x
+ dx, 0] |> int
980 let g = img.Data.[y
+ dy
, x
+ dx, 1] |> int
981 let r = img.Data.[y
+ dy
, x
+ dx, 2] |> int
982 img.Data.[y
+ dy
, x
+ dx, 0] <- if b + colorB > 255 then 255uy else byte (b + colorB)
983 img.Data.[y
+ dy
, x
+ dx, 1] <- if g + colorG > 255 then 255uy else byte (g + colorG)
984 img.Data.[y
+ dy
, x
+ dx, 2] <- if r + colorR > 255 then 255uy else byte (r + colorR)
986 let crossColor, crossColor2
=
987 match c
.cellClass
with
988 | HealthyRBC -> Bgr(255., 0., 0.), Bgr(255., 255., 255.)
989 | InfectedRBC -> Bgr(0., 0., 255.), Bgr(120., 120., 255.)
990 | Peculiar -> Bgr(0., 0., 0.), Bgr(80., 80., 80.)
992 drawLine img crossColor2
(c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 2
993 drawLine img crossColor2 c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 2
995 drawLine img crossColor (c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 1
996 drawLine img crossColor c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 1
999 let drawCells (img: Image<Bgr, byte>) (drawCellContent
: bool) (cells
: Cell list) =
1000 List.iter
(fun c
-> drawCell img drawCellContent
c) cells