3fb8ecfc114ff74eddac4791852e2a5df2205226
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> * Matrix<float32> * Matrix<float32> =
176 new Matrix<float32>(array2D [[ 1.0f; 0.0f; -1.0f ]
177 [ 2.0f; 0.0f; -2.0f ]
178 [ 1.0f; 0.0f; -1.0f ]])
180 let xGradient = new Matrix<float32>(img.Size)
181 let yGradient = new Matrix<float32>(img.Size)
182 CvInvoke.Filter2D(img, xGradient, sobelKernel, Point(1, 1))
183 CvInvoke.Filter2D(img, yGradient, sobelKernel.Transpose(), Point(1, 1))
185 use magnitudes = new Matrix<float32>(xGradient.Size)
186 use angles = new Matrix<float32>(xGradient.Size)
187 CvInvoke.CartToPolar(xGradient, yGradient, magnitudes, angles) // Compute the magnitudes and angles.
189 let thresholdHigh, thresholdLow =
190 let sensibilityHigh = 0.1f
191 let sensibilityLow = 0.0f
192 let threshold, _, _ = otsu (histogramMat magnitudes 300)
193 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
195 // Non-maximum suppression.
196 use nms = new Matrix<byte>(xGradient.Size)
198 let nmsData = nms.Data
199 let anglesData = angles.Data
200 let magnitudesData = magnitudes.Data
201 let xGradientData = xGradient.Data
202 let yGradientData = yGradient.Data
204 for i in 0 .. h - 1 do
205 nmsData.[i, 0] <- 0uy
206 nmsData.[i, w - 1] <- 0uy
208 for j in 0 .. w - 1 do
209 nmsData.[0, j] <- 0uy
210 nmsData.[h - 1, j] <- 0uy
212 for i in 1 .. h - 2 do
213 for j in 1 .. w - 2 do
214 let vx = xGradientData.[i, j]
215 let vy = yGradientData.[i, j]
216 if vx <> 0.f || vy <> 0.f
218 let angle = anglesData.[i, j]
220 let vx', vy' = abs vx, abs vy
221 let ratio2 = if vx' > vy' then vy' / vx' else vx' / vy'
222 let ratio1 = 1.f - ratio2
224 let mNeigbors (sign: int) : float32 =
226 then ratio1 * magnitudesData.[i, j + sign] + ratio2 * magnitudesData.[i + sign, j + sign]
227 elif angle < PI / 2.f
228 then ratio2 * magnitudesData.[i + sign, j + sign] + ratio1 * magnitudesData.[i + sign, j]
229 elif angle < 3.f * PI / 4.f
230 then ratio1 * magnitudesData.[i + sign, j] + ratio2 * magnitudesData.[i + sign, j - sign]
232 then ratio2 * magnitudesData.[i + sign, j - sign] + ratio1 * magnitudesData.[i, j - sign]
233 elif angle < 5.f * PI / 4.f
234 then ratio1 * magnitudesData.[i, j - sign] + ratio2 * magnitudesData.[i - sign, j - sign]
235 elif angle < 3.f * PI / 2.f
236 then ratio2 * magnitudesData.[i - sign, j - sign] + ratio1 * magnitudesData.[i - sign, j]
237 elif angle < 7.f * PI / 4.f
238 then ratio1 * magnitudesData.[i - sign, j] + ratio2 * magnitudesData.[i - sign, j + sign]
239 else ratio2 * magnitudesData.[i - sign, j + sign] + ratio1 * magnitudesData.[i, j + sign]
241 let m = magnitudesData.[i, j]
242 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
244 nmsData.[i, j] <- 1uy
246 // suppressMConnections nms // It's
not helpful
for the rest of the process (ellipse
detection).
248 let edges = new Matrix<byte
>(xGradient.Size)
249 let edgesData = edges.Data
251 // Hysteresis thresholding.
252 let toVisit = Stack<Point>()
253 for i
in 0 .. h - 1 do
254 for j
in 0 .. w - 1 do
255 if nmsData.[i
, j
] = 1uy && magnitudesData.[i
, j
] >= thresholdHigh
257 nmsData.[i
, j
] <- 0uy
258 toVisit.Push(Point(j
, i
))
259 while toVisit.Count > 0 do
260 let p = toVisit.Pop()
261 edgesData.[p.Y, p.X] <- 1uy
264 if i
' <> 0 || j' <> 0
268 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
270 nmsData.[ni, nj] <- 0uy
271 toVisit.Push(Point(nj, ni))
273 edges, xGradient, yGradient
275 let gaussianFilter (img : Image<'TColor, 'TDepth>) (standardDeviation
: float) : Image<'TColor, 'TDepth> =
276 let size = 2 * int (ceil
(4.0 * standardDeviation
)) + 1
277 img.SmoothGaussian(size, size, standardDeviation
, standardDeviation
)
279 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
281 img.Data.[p.Y, p.X, 0] <- intensity
287 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
290 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
292 let imgData = img.Data
293 let suppress: bool[,] = Array2D.zeroCreate h w
295 let result = List<List<Point>>()
297 let flood (start: Point) : List<List<Point>> =
298 let sameLevelToCheck = Stack<Point>()
299 let betterLevelToCheck = Stack<Point>()
300 betterLevelToCheck.Push(start)
302 let result' = List<List<Point>>()
304 while betterLevelToCheck.Count > 0 do
305 let p = betterLevelToCheck.Pop()
306 if not suppress.[p.Y, p.X]
308 suppress.[p.Y, p.X] <- true
309 sameLevelToCheck.Push(p)
310 let current = List<Point>()
312 let mutable betterExists = false
314 while sameLevelToCheck.Count > 0 do
315 let p' = sameLevelToCheck.Pop()
316 let currentLevel = imgData.[p'.Y, p'.X, 0]
317 current.Add(p') |> ignore
321 if ni >= 0 && ni < h && nj >= 0 && nj < w
323 let level = imgData.[ni, nj, 0]
324 let notSuppressed = not suppress.[ni, nj]
326 if level = currentLevel && notSuppressed
328 suppress.[ni, nj] <- true
329 sameLevelToCheck.Push(Point(nj, ni))
330 elif
if extremumType
= ExtremumType.Maxima then level > currentLevel else level < currentLevel
335 betterLevelToCheck.Push(Point(nj, ni))
342 for i
in 0 .. h - 1 do
343 for j in 0 .. w - 1 do
344 let maxima = flood (Point(j, i
))
347 result.AddRange(maxima)
349 result.Select(fun l
-> Points(l
))
351 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
352 findExtremum img ExtremumType.Maxima
354 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
355 findExtremum img ExtremumType.Minima
357 type PriorityQueue () =
359 let q: Points[] = Array.init
size (fun i
-> Points())
360 let mutable highest = -1 // Value of the first elements of 'q'.
361 let mutable lowest = size
363 member this
.NextMax () : byte
* Point =
366 invalidOp
"Queue is empty"
370 l.Remove(next) |> ignore
371 let value = byte
highest
375 highest <- highest - 1
376 while highest > lowest && q.[highest].Count = 0 do
377 highest <- highest - 1
385 member this
.NextMin () : byte
* Point =
388 invalidOp
"Queue is empty"
390 let l = q.[lowest + 1]
392 l.Remove(next) |> ignore
393 let value = byte
(lowest + 1)
398 while lowest < highest && q.[lowest + 1].Count = 0 do
413 member this
.Add (value: byte
) (p: Point) =
423 q.[vi].Add(p) |> ignore
425 member this
.Remove (value: byte
) (p: Point) =
427 if q.[vi].Remove(p) && q.[vi].Count = 0
431 highest <- highest - 1
432 while highest > lowest && q.[highest].Count = 0 do
433 highest <- highest - 1
437 while lowest < highest && q.[lowest + 1].Count = 0 do
440 if highest = lowest // The queue is now empty.
445 member this
.IsEmpty =
448 member this
.Clear () =
449 while highest > lowest do
451 highest <- highest - 1
455 type private AreaState =
460 type private AreaOperation =
465 type private Area (elements
: Points) =
466 member this
.Elements = elements
467 member val Intensity = None with get
, set
468 member val State = AreaState.Unprocessed with get
, set
470 let private areaOperation
(img: Image<Gray, byte
>) (area
: int) (op
: AreaOperation) =
473 let imgData = img.Data
474 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
476 let areas = List<Area>((if op
= AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map
Area)
478 let pixels: Area[,] = Array2D.create
h w null
480 for e
in m.Elements do
481 pixels.[e
.Y, e
.X] <- m
483 let queue = PriorityQueue()
485 let addEdgeToQueue (elements
: Points) =
490 let p' = Point(nj, ni)
491 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
493 queue.Add (imgData.[ni, nj, 0]) p'
495 // Reverse order is quicker.
496 for i in areas.Count - 1 .. -1 .. 0 do
498 if m.Elements.Count <= area && m.State <> AreaState.Removed
501 addEdgeToQueue m.Elements
503 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
504 let nextElements = Points()
506 let mutable stop = false
508 let intensity', p = if op
= AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
509 let mutable merged = false
511 if intensity' = intensity // The intensity doesn't
change.
513 if m.Elements.Count + nextElements.Count + 1 > area
515 m.State <- AreaState.Validated
516 m.Intensity <- Some intensity
519 nextElements.Add(p) |> ignore
521 elif
if op
= AreaOperation.Opening then intensity' < intensity else intensity' > intensity
523 m.Elements.UnionWith(nextElements)
524 for e
in nextElements do
525 pixels.[e
.Y, e
.X] <- m
527 if m.Elements.Count = area
529 m.State <- AreaState.Validated
530 m.Intensity <- Some (intensity')
533 intensity <- intensity'
535 nextElements.Add(p) |> ignore
538 match pixels.[p.Y, p.X] with
541 if m'.Elements.Count + m.Elements.Count <= area
543 m'.State <- AreaState.Removed
544 for e in m'.Elements do
545 pixels.[e
.Y, e
.X] <- m
546 queue.Remove imgData.[e
.Y, e
.X, 0] e
547 addEdgeToQueue m'.Elements
548 m.Elements.UnionWith(m'.Elements)
549 let intensityMax = if op
= AreaOperation.Opening then queue.Max else queue.Min
550 if intensityMax <> intensity
552 intensity <- intensityMax
558 m.State <- AreaState.Validated
559 m.Intensity <- Some (intensity)
562 if not stop && not merged
567 let p' = Point(nj, ni)
568 if ni < 0 || ni >= h || nj < 0 || nj >= w
570 m.State <- AreaState.Validated
571 m.Intensity <- Some (intensity)
573 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
575 queue.Add (imgData.[ni, nj, 0]) p'
579 if m.Elements.Count + nextElements.Count <= area
581 m.State <- AreaState.Validated
582 m.Intensity <- Some intensity'
583 m.Elements.UnionWith(nextElements)
587 if m.State = AreaState.Validated
589 match m.Intensity with
591 for p in m.Elements do
592 imgData.[p.Y, p.X, 0] <- i
597 /// Area opening on byte image.
599 let areaOpen (img: Image<Gray, byte>) (area: int) =
600 areaOperation img area AreaOperation.Opening
603 /// Area closing on byte image.
605 let areaClose (img: Image<Gray, byte>) (area: int) =
606 areaOperation img area AreaOperation.Closing
608 // A simpler algorithm than 'areaOpen' on byte image but slower.
609 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
612 let imgData = img.Data
613 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
615 let histogram = Array.zeroCreate 256
616 for i in 0 .. h - 1 do
617 for j in 0 .. w - 1 do
618 let v = imgData.[i, j, 0] |> int
619 histogram.[v] <- histogram.[v] + 1
621 let flooded : bool[,] = Array2D.zeroCreate h w
623 let pointsChecked = HashSet<Point>()
624 let pointsToCheck = Stack<Point>()
626 for level in 255 .. -1 .. 0 do
627 let mutable n = histogram.[level]
630 for i in 0 .. h - 1 do
631 for j in 0 .. w - 1 do
632 if not flooded.[i, j] && imgData.[i, j, 0] = byte level
634 let mutable maxNeighborValue = 0uy
635 pointsChecked.Clear()
636 pointsToCheck.Clear()
637 pointsToCheck.Push(Point(j, i))
639 while pointsToCheck.Count > 0 do
640 let next = pointsToCheck.Pop()
641 pointsChecked.Add(next) |> ignore
642 flooded.[next.Y, next.X] <- true
645 let p = Point(next.X + nx, next.Y + ny)
646 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
648 let v = imgData.[p.Y, p.X, 0]
651 if not (pointsChecked.Contains(p))
653 pointsToCheck.Push(p)
654 elif v > maxNeighborValue
656 maxNeighborValue <- v
658 if int maxNeighborValue < level && pointsChecked.Count <= area
660 for p in pointsChecked do
661 imgData.[p.Y, p.X, 0] <- maxNeighborValue
664 type Island (cmp: IComparer<float32>) =
665 member val Shore = Heap.Heap<float32, Point>(cmp) with get
666 member val Level = 0.f with get, set
667 member val Surface = 0 with get, set
668 member this.IsInfinite = this.Surface = Int32.MaxValue
670 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: ('a -> float32 -> unit) option) (op: AreaOperation) =
674 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
676 let comparer = if op = AreaOperation.Opening
677 then { new IComparer<float32> with member this.Compare(v1, v2) = v1.CompareTo(v2) }
678 else { new IComparer<float32> with member this.Compare(v1, v2) = v2.CompareTo(v1) }
680 let ownership: Island[,] = Array2D.create h w null
682 // Initialize islands with their shore.
683 let islands = List<Island>()
684 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
688 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
690 let shorePoints = Points()
692 ownership.[p.Y, p.X] <- island
696 let neighbor = Point(nj, ni)
697 if ni >= 0 && ni < h && nj >= 0 && nj < w && Object.ReferenceEquals(ownership.[ni, nj], null) && not (shorePoints.Contains(neighbor))
699 shorePoints.Add(neighbor) |> ignore
700 island.Shore.Add earth.[ni, nj, 0] neighbor
702 for area, obj in areas do
703 for island in islands do
704 let mutable stop = island.Shore.IsEmpty
706 // 'true' if 'p' is owned or adjacent to 'island'.
707 let inline ownedOrAdjacent (p: Point) : bool =
708 ownership.[p.Y, p.X] = island ||
709 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
710 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
711 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
712 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
714 while not stop && island.Surface < area do
715 let level, next = island.Shore.Max
716 let other = ownership.[next.Y, next.X]
717 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
719 island.Shore.RemoveNext ()
721 if not <| Object.ReferenceEquals(other, null)
722 then // We touching another island.
723 if island.IsInfinite || other.IsInfinite || island.Surface + other.Surface >= area
726 else // We can merge 'other' into 'surface
'.
727 island.Surface <- island.Surface + other.Surface
728 island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then island.Level else other.Level
729 for l, p in other.Shore do
730 let mutable currentY = p.Y + 1
731 while currentY < h && ownership.[currentY, p.X] = other do
732 ownership.[currentY, p.X] <- island
733 currentY <- currentY + 1
737 elif comparer.Compare(level, island.Level) > 0
741 island.Shore.RemoveNext ()
745 if ni < 0 || ni >= h || nj < 0 || nj >= w
747 island.Surface <- Int32.MaxValue
750 let neighbor = Point(nj, ni)
751 if not <| ownedOrAdjacent neighbor
753 island.Shore.Add earth.[ni, nj, 0] neighbor
756 ownership.[next.Y, next.X] <- island
757 island.Level <- level
758 island.Surface <- island.Surface + 1
760 let mutable diff = 0.f
762 for i in 0 .. h - 1 do
763 for j in 0 .. w - 1 do
764 match ownership.[i, j] with
768 diff <- diff + l - earth.[i, j, 0]
772 | Some f' -> f
' obj diff
777 /// Area opening on float image.
779 let areaOpenF (img: Image<Gray, float32>) (area: int) =
780 areaOperationF img [ area, () ] None AreaOperation.Opening
783 /// Area closing on float image.
785 let areaCloseF (img: Image<Gray, float32>) (area: int) =
786 areaOperationF img [ area, () ] None AreaOperation.Closing
789 /// Area closing on float image with different areas. Given areas must be sorted increasingly.
790 /// For each area the function 'f
' is called with the associated area value of type 'a
and the volume difference
791 /// Between the previous and the current closing.
793 let areaOpenFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
794 areaOperationF
img areas (Some f) AreaOperation.Opening
797 /// Same as 'areaOpenFWithFun' for closing operation.
799 let areaCloseFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
800 areaOperationF
img areas (Some f) AreaOperation.Closing
803 /// Zhang and Suen thinning algorithm.
804 /// Modify 'mat' in place.
806 let thin (mat
: Matrix<byte
>) =
809 let mutable data1 = mat
.Data
810 let mutable data2 = Array2D.copy
data1
812 let mutable pixelChanged = true
813 let mutable oddIteration = true
815 while pixelChanged do
816 pixelChanged <- false
819 if data1.[i
, j] = 1uy
821 let p2 = if i
= 0 then 0uy else data1.[i
-1, j]
822 let p3 = if i
= 0 || j = w-1 then 0uy else data1.[i
-1, j+1]
823 let p4 = if j = w-1 then 0uy else data1.[i
, j+1]
824 let p5 = if i
= h-1 || j = w-1 then 0uy else data1.[i
+1, j+1]
825 let p6 = if i
= h-1 then 0uy else data1.[i
+1, j]
826 let p7 = if i
= h-1 || j = 0 then 0uy else data1.[i
+1, j-1]
827 let p8 = if j = 0 then 0uy else data1.[i
, j-1]
828 let p9 = if i
= 0 || j = 0 then 0uy else data1.[i
-1, j-1]
830 let sumNeighbors = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
831 if sumNeighbors >= 2uy && sumNeighbors <= 6uy &&
832 (if p2 = 0uy && p3 = 1uy then 1 else 0) +
833 (if p3 = 0uy && p4 = 1uy then 1 else 0) +
834 (if p4 = 0uy && p5 = 1uy then 1 else 0) +
835 (if p5 = 0uy && p6 = 1uy then 1 else 0) +
836 (if p6 = 0uy && p7 = 1uy then 1 else 0) +
837 (if p7 = 0uy && p8 = 1uy then 1 else 0) +
838 (if p8 = 0uy && p9 = 1uy then 1 else 0) +
839 (if p9 = 0uy && p2 = 1uy then 1 else 0) = 1 &&
841 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
842 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
849 oddIteration <- not oddIteration
855 /// Remove all 8-connected pixels with an area equal or greater than 'areaSize'.
856 /// Modify 'mat' in place.
858 let removeArea (mat
: Matrix<byte
>) (areaSize
: int) =
869 use mat' = new Matrix<byte>(mat.Size)
875 let data' = mat'.Data
879 if data'.[i, j] = 1uy
881 let neighborhood = List<Point>()
882 let neighborsToCheck = Stack<Point>()
883 neighborsToCheck.Push(Point(j, i))
886 while neighborsToCheck.Count > 0 do
887 let n = neighborsToCheck.Pop()
889 for (ni, nj) in neighbors do
892 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
894 neighborsToCheck.Push(Point(pj, pi))
895 data'.[pi, pj] <- 0uy
896 if neighborhood.Count <= areaSize
898 for n in neighborhood do
899 data.[n.Y, n.X] <- 0uy
901 let connectedComponents (img: Image<Gray, byte
>) (startPoints
: List<Point>) : Points =
905 let pointChecked = Points()
906 let pointToCheck = Stack<Point>(startPoints
);
910 while pointToCheck.Count > 0 do
911 let next = pointToCheck.Pop()
912 pointChecked.Add(next) |> ignore
915 if ny
<> 0 && nx
<> 0
917 let p = Point(next.X + nx
, next.Y + ny
)
918 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)
924 let drawLine (img: Image<'TColor, 'TDepth>) (color
: 'TColor) (x0: int) (y0: int) (x1: int) (y1: int) (thickness: int) =
925 img.Draw(LineSegment2D(Point(x0, y0), Point(x1, y1)), color, thickness);
927 let drawLineF (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0
: float) (y0
: float) (x1
: float) (y1
: float) (thickness
: int) =
928 img.Draw(LineSegment2DF(PointF(float32 x0
, float32 y0
), PointF(float32 x1
, float32 y1
)), color
, thickness
, CvEnum.LineType.AntiAlias);
930 let drawEllipse (img: Image<'TColor, 'TDepth>) (e
: Ellipse) (color
: 'TColor) (alpha: float) =
933 img.Draw(Emgu.CV.Structure.Ellipse(PointF(e.Cx, e.Cy), SizeF(2.f * e.B, 2.f * e.A), e.Alpha / PI * 180.f), color, 1, CvEnum.LineType.AntiAlias)
935 let windowPosX = e.Cx - e.A - 5.f
936 let gapX = windowPosX - (float32 (int windowPosX))
938 let windowPosY = e.Cy - e.A - 5.f
939 let gapY = windowPosY - (float32 (int windowPosY))
941 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e.A + 5.f) |> int, 2.f * (e.A + 5.f) |> int)
944 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
946 use i = new Image<'TColor, 'TDepth>(img.ROI.Size)
947 i.Draw(Emgu.CV.Structure.Ellipse(PointF(e.A + 5.f + gapX, e.A + 5.f + gapY), SizeF(2.f * e.B, 2.f * e.A), e.Alpha / PI * 180.f), color, 1, CvEnum.LineType.AntiAlias)
948 CvInvoke.AddWeighted(img, 1.0, i, alpha, 0.0, img)
949 img.ROI <- Rectangle.Empty
951 let drawEllipses (img: Image<'TColor, 'TDepth>) (ellipses: Ellipse list) (color: 'TColor) (alpha
: float) =
952 List.iter
(fun e
-> drawEllipse img e
color alpha
) ellipses
954 let rngCell = System.Random()
955 let drawCell (img: Image<Bgr, byte
>) (drawCellContent
: bool) (c
: Cell) =
958 let colorB = rngCell.Next(20, 70)
959 let colorG = rngCell.Next(20, 70)
960 let colorR = rngCell.Next(20, 70)
962 for y
in 0 .. c
.elements
.Height - 1 do
963 for x
in 0 .. c
.elements
.Width - 1 do
964 if c
.elements
.[y
, x
] > 0uy
966 let dx, dy
= c
.center
.X - c
.elements
.Width / 2, c
.center
.Y - c
.elements
.Height / 2
967 let b = img.Data.[y
+ dy
, x
+ dx, 0] |> int
968 let g = img.Data.[y
+ dy
, x
+ dx, 1] |> int
969 let r = img.Data.[y
+ dy
, x
+ dx, 2] |> int
970 img.Data.[y
+ dy
, x
+ dx, 0] <- if b + colorB > 255 then 255uy else byte (b + colorB)
971 img.Data.[y
+ dy
, x
+ dx, 1] <- if g + colorG > 255 then 255uy else byte (g + colorG)
972 img.Data.[y
+ dy
, x
+ dx, 2] <- if r + colorR > 255 then 255uy else byte (r + colorR)
974 let crossColor, crossColor2
=
975 match c
.cellClass
with
976 | HealthyRBC -> Bgr(255., 0., 0.), Bgr(255., 255., 255.)
977 | InfectedRBC -> Bgr(0., 0., 255.), Bgr(120., 120., 255.)
978 | Peculiar -> Bgr(0., 0., 0.), Bgr(80., 80., 80.)
980 drawLine img crossColor2
(c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 2
981 drawLine img crossColor2 c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 2
983 drawLine img crossColor (c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 1
984 drawLine img crossColor c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 1
987 let drawCells (img: Image<Bgr, byte>) (drawCellContent
: bool) (cells
: Cell list) =
988 List.iter
(fun c
-> drawCell img drawCellContent
c) cells