1
module ParasitemiaCore.ImgTools
5 open System.Collections.Generic
15 // Normalize image values between 0uy and 255uy.
16 let normalizeAndConvert (img
: Image<Gray, 'TDepth>) : Image<Gray, byte> =
17 let min = ref [| 0.0 |]
18 let minLocation = ref <| [| Point() |]
19 let max = ref [| 0.0 |]
20 let maxLocation = ref <| [| Point() |]
21 img.MinMax(min, max, minLocation, maxLocation)
22 ((img.Convert<Gray, float32>() - (!min).[0]) / ((!max).[0] - (!min).[0]) * 255.0).Convert<Gray, byte>()
24 let saveImg (img: Image<'TColor, 'TDepth>) (filepath: string) =
27 let saveMat (mat: Matrix<'TDepth>) (filepath
: string) =
28 use img = new Image<Gray, 'TDeph>(mat.Size)
32 type Histogram = { data: int[]; total: int; sum: int; min: float32; max: float32 }
34 let histogramImg (img: Image<Gray, float32>) (nbSamples: int) : Histogram =
35 let imgData = img.Data
38 let min = ref [| 0.0 |]
39 let minLocation = ref <| [| Point() |]
40 let max = ref [| 0.0 |]
41 let maxLocation = ref <| [| Point() |]
42 img.MinMax(min, max, minLocation, maxLocation)
43 float32 (!min).[0], float32 (!max).[0]
45 let bin (x: float32) : int =
46 let p = int ((x - min) / (max - min) * float32 nbSamples)
47 if p >= nbSamples then nbSamples - 1 else p
49 let data = Array.zeroCreate nbSamples
51 for i in 0 .. img.Height - 1 do
52 for j in 0 .. img.Width - 1 do
53 let p = bin imgData.[i, j, 0]
54 data.[p] <- data.[p] + 1
56 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
58 let histogramMat (mat: Matrix<float32>) (nbSamples: int) : Histogram =
59 let matData = mat.Data
63 let minLocation = ref <| Point()
65 let maxLocation = ref <| Point()
66 mat.MinMax(min, max, minLocation, maxLocation)
67 float32 !min, float32 !max
69 let bin (x: float32) : int =
70 let p = int ((x - min) / (max - min) * float32 nbSamples)
71 if p >= nbSamples then nbSamples - 1 else p
73 let data = Array.zeroCreate nbSamples
75 for i in 0 .. mat.Height - 1 do
76 for j in 0 .. mat.Width - 1 do
77 let p = bin matData.[i, j]
78 data.[p] <- data.[p] + 1
80 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
82 let histogram (values: float32 seq) (nbSamples: int) : Histogram =
83 let mutable min = Single.MaxValue
84 let mutable max = Single.MinValue
89 if v < min then min <- v
90 if v > max then max <- v
92 let bin (x: float32) : int =
93 let p = int ((x - min) / (max - min) * float32 nbSamples)
94 if p >= nbSamples then nbSamples - 1 else p
96 let data = Array.zeroCreate nbSamples
100 data.[p] <- data.[p] + 1
102 { data = data; total = n; sum = Array.sum data; min = min; max = max }
104 let otsu (hist: Histogram) : float32 * float32 * float32 =
107 let mutable maximum = 0.0
108 let mutable level = 0
109 let sum = hist.data |> Array.mapi (fun i v -> i * v) |> Array.sum |> float
111 for i in 0 .. hist.data.Length - 1 do
112 wB <- wB + hist.data.[i]
115 let wF = hist.total - wB
118 sumB <- sumB + i * hist.data.[i]
119 let mB = (float sumB) / (float wB)
120 let mF = (sum - float sumB) / (float wF)
121 let between = (float wB) * (float wF) * (mB - mF) ** 2.;
122 if between >= maximum
130 for i in 0 .. level - 1 do
131 sum <- sum + i * hist.data.[i]
132 nb <- nb + hist.data.[i]
133 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
138 for i in level + 1 .. hist.data.Length - 1 do
139 sum <- sum + i * hist.data.[i]
140 nb <- nb + hist.data.[i]
141 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
144 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
146 toFloat level, toFloat mean1, toFloat mean2
148 let suppressMConnections (img: Matrix<byte>) =
151 for i in 1 .. h - 2 do
152 for j in 1 .. w - 2 do
153 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)
156 for i in 1 .. h - 2 do
157 for j in 1 .. w - 2 do
158 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)
162 let findEdges (img: Image<Gray, float32>) : Matrix<byte> * Image<Gray, float32> * Image<Gray, float32> =
167 new ConvolutionKernelF(array2D [[ 1.0f; 0.0f; -1.0f ]
168 [ 2.0f; 0.0f; -2.0f ]
169 [ 1.0f; 0.0f; -1.0f ]], Point(1, 1))
171 let xGradient = img.Convolution(sobelKernel)
172 let yGradient = img.Convolution(sobelKernel.Transpose())
174 let xGradientData = xGradient.Data
175 let yGradientData = yGradient.Data
176 for r in 0 .. h - 1 do
177 xGradientData.[r, 0, 0] <- 0.f
178 xGradientData.[r, w - 1, 0] <- 0.f
179 yGradientData.[r, 0, 0] <- 0.f
180 yGradientData.[r, w - 1, 0] <- 0.f
182 for c in 0 .. w - 1 do
183 xGradientData.[0, c, 0] <- 0.f
184 xGradientData.[h - 1, c, 0] <- 0.f
185 yGradientData.[0, c, 0] <- 0.f
186 yGradientData.[h - 1, c, 0] <- 0.f
188 use magnitudes = new Matrix<float32>(xGradient.Size)
189 use angles = new Matrix<float32>(xGradient.Size)
190 CvInvoke.CartToPolar(xGradient, yGradient, magnitudes, angles) // Compute the magnitudes (without angles).
192 let thresholdHigh, thresholdLow =
193 let sensibilityHigh = 0.1f
194 let sensibilityLow = 0.0f
195 use magnitudesByte = magnitudes.Convert<byte>()
196 let threshold, _, _ = otsu (histogramMat magnitudes 300)
197 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
199 // Non-maximum suppression.
200 use nms = new Matrix<byte>(xGradient.Size)
202 let nmsData = nms.Data
203 let anglesData = angles.Data
204 let magnitudesData = magnitudes.Data
205 let xGradientData = xGradient.Data
206 let yGradientData = yGradient.Data
208 let PI = float32 Math.PI
210 for i in 0 .. h - 1 do
211 nmsData.[i, 0] <- 0uy
212 nmsData.[i, w - 1] <- 0uy
214 for j in 0 .. w - 1 do
215 nmsData.[0, j] <- 0uy
216 nmsData.[h - 1, j] <- 0uy
218 for i in 1 .. h - 2 do
219 for j in 1 .. w - 2 do
220 let vx = xGradientData.[i, j, 0]
221 let vy = yGradientData.[i, j, 0]
222 if vx <> 0.f || vy <> 0.f
224 let angle = anglesData.[i, j]
226 let vx', vy' = abs vx, abs vy
227 let ratio2 = if vx' > vy' then vy' / vx' else vx' / vy'
228 let ratio1 = 1.f - ratio2
230 let mNeigbors (sign: int) : float32 =
232 then ratio1 * magnitudesData.[i, j + sign] + ratio2 * magnitudesData.[i + sign, j + sign]
233 elif angle < PI / 2.f
234 then ratio2 * magnitudesData.[i + sign, j + sign] + ratio1 * magnitudesData.[i + sign, j]
235 elif angle < 3.f * PI / 4.f
236 then ratio1 * magnitudesData.[i + sign, j] + ratio2 * magnitudesData.[i + sign, j - sign]
238 then ratio2 * magnitudesData.[i + sign, j - sign] + ratio1 * magnitudesData.[i, j - sign]
239 elif angle < 5.f * PI / 4.f
240 then ratio1 * magnitudesData.[i, j - sign] + ratio2 * magnitudesData.[i - sign, j - sign]
241 elif angle < 3.f * PI / 2.f
242 then ratio2 * magnitudesData.[i - sign, j - sign] + ratio1 * magnitudesData.[i - sign, j]
243 elif angle < 7.f * PI / 4.f
244 then ratio1 * magnitudesData.[i - sign, j] + ratio2 * magnitudesData.[i - sign, j + sign]
245 else ratio2 * magnitudesData.[i - sign, j + sign] + ratio1 * magnitudesData.[i, j + sign]
247 let m = magnitudesData.[i, j]
248 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
250 nmsData.[i, j] <- 1uy
252 // suppressMConnections nms // It's
not helpful
for the rest of the process (ellipse
detection).
254 let edges = new Matrix<byte
>(xGradient.Size)
255 let edgesData = edges.Data
257 // Hysteresis thresholding.
258 let toVisit = Stack<Point>()
259 for i
in 0 .. h - 1 do
260 for j
in 0 .. w - 1 do
261 if nmsData.[i
, j
] = 1uy && magnitudesData.[i
, j
] >= thresholdHigh
263 nmsData.[i
, j
] <- 0uy
264 toVisit.Push(Point(j
, i
))
265 while toVisit.Count > 0 do
266 let p = toVisit.Pop()
267 edgesData.[p.Y, p.X] <- 1uy
270 if i
' <> 0 || j' <> 0
274 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
276 nmsData.[ni, nj] <- 0uy
277 toVisit.Push(Point(nj, ni))
279 edges, xGradient, yGradient
281 let gaussianFilter (img : Image<'TColor, 'TDepth>) (standardDeviation
: float) : Image<'TColor, 'TDepth> =
282 let size = 2 * int (ceil
(4.0 * standardDeviation
)) + 1
283 img.SmoothGaussian(size, size, standardDeviation
, standardDeviation
)
285 type Points = HashSet<Point>
287 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
289 img.Data.[p.Y, p.X, 0] <- intensity
295 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
298 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
300 let imgData = img.Data
301 let suppress: bool[,] = Array2D.zeroCreate h w
303 let result = List<List<Point>>()
305 let flood (start: Point) : List<List<Point>> =
306 let sameLevelToCheck = Stack<Point>()
307 let betterLevelToCheck = Stack<Point>()
308 betterLevelToCheck.Push(start)
310 let result' = List<List<Point>>()
312 while betterLevelToCheck.Count > 0 do
313 let p = betterLevelToCheck.Pop()
314 if not suppress.[p.Y, p.X]
316 suppress.[p.Y, p.X] <- true
317 sameLevelToCheck.Push(p)
318 let current = List<Point>()
320 let mutable betterExists = false
322 while sameLevelToCheck.Count > 0 do
323 let p' = sameLevelToCheck.Pop()
324 let currentLevel = imgData.[p'.Y, p'.X, 0]
325 current.Add(p') |> ignore
329 if ni >= 0 && ni < h && nj >= 0 && nj < w
331 let level = imgData.[ni, nj, 0]
332 let notSuppressed = not suppress.[ni, nj]
334 if level = currentLevel && notSuppressed
336 suppress.[ni, nj] <- true
337 sameLevelToCheck.Push(Point(nj, ni))
338 elif
if extremumType
= ExtremumType.Maxima then level > currentLevel else level < currentLevel
343 betterLevelToCheck.Push(Point(nj, ni))
350 for i
in 0 .. h - 1 do
351 for j in 0 .. w - 1 do
352 let maxima = flood (Point(j, i
))
355 result.AddRange(maxima)
357 result.Select(fun l
-> Points(l
))
359 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
360 findExtremum img ExtremumType.Maxima
362 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
363 findExtremum img ExtremumType.Minima
365 type PriorityQueue () =
367 let q: Points[] = Array.init
size (fun i
-> Points())
368 let mutable highest = -1 // Value of the first elements of 'q'.
369 let mutable lowest = size
371 member this
.NextMax () : byte
* Point =
374 invalidOp
"Queue is empty"
378 l.Remove(next) |> ignore
379 let value = byte
highest
383 highest <- highest - 1
384 while highest > lowest && q.[highest].Count = 0 do
385 highest <- highest - 1
393 member this
.NextMin () : byte
* Point =
396 invalidOp
"Queue is empty"
398 let l = q.[lowest + 1]
400 l.Remove(next) |> ignore
401 let value = byte
(lowest + 1)
406 while lowest < highest && q.[lowest + 1].Count = 0 do
421 member this
.Add (value: byte
) (p: Point) =
431 q.[vi].Add(p) |> ignore
433 member this
.Remove (value: byte
) (p: Point) =
435 if q.[vi].Remove(p) && q.[vi].Count = 0
439 highest <- highest - 1
440 while highest > lowest && q.[highest].Count = 0 do
441 highest <- highest - 1
445 while lowest < highest && q.[lowest + 1].Count = 0 do
448 if highest = lowest // The queue is now empty.
453 member this
.IsEmpty =
456 member this
.Clear () =
457 while highest > lowest do
459 highest <- highest - 1
463 type private AreaState =
468 type private AreaOperation =
473 type private Area (elements
: Points) =
474 member this
.Elements = elements
475 member val Intensity = None with get
, set
476 member val State = AreaState.Unprocessed with get
, set
478 let private areaOperation
(img: Image<Gray, byte
>) (area
: int) (op
: AreaOperation) =
481 let imgData = img.Data
482 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
484 let areas = List<Area>((if op
= AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map
Area)
486 let pixels: Area[,] = Array2D.create
h w null
488 for e
in m.Elements do
489 pixels.[e
.Y, e
.X] <- m
491 let queue = PriorityQueue()
493 let addEdgeToQueue (elements
: Points) =
498 let p' = Point(nj, ni)
499 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
501 queue.Add (imgData.[ni, nj, 0]) p'
503 // Reverse order is quicker.
504 for i in areas.Count - 1 .. -1 .. 0 do
506 if m.Elements.Count <= area && m.State <> AreaState.Removed
509 addEdgeToQueue m.Elements
511 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
512 let nextElements = Points()
514 let mutable stop = false
516 let intensity', p = if op
= AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
517 let mutable merged = false
519 if intensity' = intensity // The intensity doesn't
change.
521 if m.Elements.Count + nextElements.Count + 1 > area
523 m.State <- AreaState.Validated
524 m.Intensity <- Some intensity
527 nextElements.Add(p) |> ignore
529 elif
if op
= AreaOperation.Opening then intensity' < intensity else intensity' > intensity
531 m.Elements.UnionWith(nextElements)
532 for e
in nextElements do
533 pixels.[e
.Y, e
.X] <- m
535 if m.Elements.Count = area
537 m.State <- AreaState.Validated
538 m.Intensity <- Some (intensity')
541 intensity <- intensity'
543 nextElements.Add(p) |> ignore
546 match pixels.[p.Y, p.X] with
549 if m'.Elements.Count + m.Elements.Count <= area
551 m'.State <- AreaState.Removed
552 for e in m'.Elements do
553 pixels.[e
.Y, e
.X] <- m
554 queue.Remove imgData.[e
.Y, e
.X, 0] e
555 addEdgeToQueue m'.Elements
556 m.Elements.UnionWith(m'.Elements)
557 let intensityMax = if op
= AreaOperation.Opening then queue.Max else queue.Min
558 if intensityMax <> intensity
560 intensity <- intensityMax
566 m.State <- AreaState.Validated
567 m.Intensity <- Some (intensity)
570 if not stop && not merged
575 let p' = Point(nj, ni)
576 if ni < 0 || ni >= h || nj < 0 || nj >= w
578 m.State <- AreaState.Validated
579 m.Intensity <- Some (intensity)
581 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
583 queue.Add (imgData.[ni, nj, 0]) p'
587 if m.Elements.Count + nextElements.Count <= area
589 m.State <- AreaState.Validated
590 m.Intensity <- Some intensity'
591 m.Elements.UnionWith(nextElements)
595 if m.State = AreaState.Validated
597 match m.Intensity with
599 for p in m.Elements do
600 imgData.[p.Y, p.X, 0] <- i
604 let areaOpen (img: Image<Gray, byte>) (area: int) =
605 areaOperation img area AreaOperation.Opening
607 let areaClose (img: Image<Gray, byte>) (area: int) =
608 areaOperation img area AreaOperation.Closing
611 type Island (cmp: IComparer<float32>) =
612 member val Shore = Heap.Heap<float32, Point>(cmp) with get
613 member val Level = 0.f with get, set
614 member val Surface = 0 with get, set
616 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: ('a -> float32 -> unit) option) (op: AreaOperation) =
620 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
622 let comparer = if op = AreaOperation.Opening
623 then { new IComparer<float32> with member this.Compare(v1, v2) = v1.CompareTo(v2) }
624 else { new IComparer<float32> with member this.Compare(v1, v2) = v2.CompareTo(v1) }
626 let ownership: Island[,] = Array2D.create h w null
628 // Initialize islands with their shore.
629 let islands = List<Island>()
630 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
634 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
636 let shorePoints = Points()
638 ownership.[p.Y, p.X] <- island
642 let neighbor = Point(nj, ni)
643 if ni >= 0 && ni < h && nj >= 0 && nj < w && Object.ReferenceEquals(ownership.[ni, nj], null) && not (shorePoints.Contains(neighbor))
645 shorePoints.Add(neighbor) |> ignore
646 island.Shore.Add earth.[ni, nj, 0] neighbor
648 for area, obj in areas do
649 for island in islands do
650 let mutable stop = island.Shore.IsEmpty
652 // 'true' if 'p' is owned or adjacent to 'island'.
653 let inline ownedOrAdjacent (p: Point) : bool =
654 ownership.[p.Y, p.X] = island ||
655 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
656 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
657 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
658 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
660 while not stop && island.Surface < area do
661 let level, next = island.Shore.Max
662 let other = ownership.[next.Y, next.X]
663 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
665 island.Shore.RemoveNext ()
667 if not <| Object.ReferenceEquals(other, null)
668 then // We touching another island.
669 if island.Surface + other.Surface >= area
672 else // We can merge 'other' into 'surface
'.
673 island.Surface <- island.Surface + other.Surface
674 island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then island.Level else other.Level
675 for l, p in other.Shore do
676 let mutable currentY = p.Y + 1
677 while currentY < h && ownership.[currentY, p.X] = other do
678 ownership.[currentY, p.X] <- island
679 currentY <- currentY + 1
683 elif comparer.Compare(level, island.Level) > 0
687 island.Shore.RemoveNext ()
691 if ni < 0 || ni >= h || nj < 0 || nj >= w
693 island.Surface <- Int32.MaxValue
696 let neighbor = Point(nj, ni)
697 if not <| ownedOrAdjacent neighbor
699 island.Shore.Add earth.[ni, nj, 0] neighbor
702 ownership.[next.Y, next.X] <- island
703 island.Level <- level
704 island.Surface <- island.Surface + 1
706 let mutable diff = 0.f
708 for i in 0 .. h - 1 do
709 for j in 0 .. w - 1 do
710 match ownership.[i, j] with
714 diff <- diff + l - earth.[i, j, 0]
718 | Some f' -> f
' obj diff
722 let areaOpenF (img: Image<Gray, float32>) (area: int) =
723 areaOperationF img [ area, () ] None AreaOperation.Opening
725 let areaCloseF (img: Image<Gray, float32>) (area: int) =
726 areaOperationF img [ area, () ] None AreaOperation.Closing
728 let areaOpenFWithFun (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: 'a -> float32 -> unit) =
729 areaOperationF img areas (Some f) AreaOperation.Opening
731 let areaCloseFWithFun (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f: 'a -> float32 -> unit) =
732 areaOperationF img areas (Some f) AreaOperation.Closing
734 // A simpler algorithm than 'areaOpen' but slower.
735 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
738 let imgData = img.Data
739 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
741 let histogram = Array.zeroCreate 256
742 for i in 0 .. h - 1 do
743 for j in 0 .. w - 1 do
744 let v = imgData.[i, j, 0] |> int
745 histogram.[v] <- histogram.[v] + 1
747 let flooded : bool[,] = Array2D.zeroCreate h w
749 let pointsChecked = HashSet<Point>()
750 let pointsToCheck = Stack<Point>()
752 for level in 255 .. -1 .. 0 do
753 let mutable n = histogram.[level]
756 for i in 0 .. h - 1 do
757 for j in 0 .. w - 1 do
758 if not flooded.[i, j] && imgData.[i, j, 0] = byte level
760 let mutable maxNeighborValue = 0uy
761 pointsChecked.Clear()
762 pointsToCheck.Clear()
763 pointsToCheck.Push(Point(j, i))
765 while pointsToCheck.Count > 0 do
766 let next = pointsToCheck.Pop()
767 pointsChecked.Add(next) |> ignore
768 flooded.[next.Y, next.X] <- true
771 let p = Point(next.X + nx, next.Y + ny)
772 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
774 let v = imgData.[p.Y, p.X, 0]
777 if not (pointsChecked.Contains(p))
779 pointsToCheck.Push(p)
780 elif v > maxNeighborValue
782 maxNeighborValue <- v
784 if int maxNeighborValue < level && pointsChecked.Count <= area
786 for p in pointsChecked do
787 imgData.[p.Y, p.X, 0] <- maxNeighborValue
789 // Zhang and Suen algorithm.
790 // Modify 'mat
' in place.
791 let thin (mat: Matrix<byte>) =
794 let mutable data1 = mat.Data
795 let mutable data2 = Array2D.copy data1
797 let mutable pixelChanged = true
798 let mutable oddIteration = true
800 while pixelChanged do
801 pixelChanged <- false
804 if data1.[i, j] = 1uy
806 let p2 = if i = 0 then 0uy else data1.[i-1, j]
807 let p3 = if i = 0 || j = w-1 then 0uy else data1.[i-1, j+1]
808 let p4 = if j = w-1 then 0uy else data1.[i, j+1]
809 let p5 = if i = h-1 || j = w-1 then 0uy else data1.[i+1, j+1]
810 let p6 = if i = h-1 then 0uy else data1.[i+1, j]
811 let p7 = if i = h-1 || j = 0 then 0uy else data1.[i+1, j-1]
812 let p8 = if j = 0 then 0uy else data1.[i, j-1]
813 let p9 = if i = 0 || j = 0 then 0uy else data1.[i-1, j-1]
815 let sumNeighbors = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
816 if sumNeighbors >= 2uy && sumNeighbors <= 6uy &&
817 (if p2 = 0uy && p3 = 1uy then 1 else 0) +
818 (if p3 = 0uy && p4 = 1uy then 1 else 0) +
819 (if p4 = 0uy && p5 = 1uy then 1 else 0) +
820 (if p5 = 0uy && p6 = 1uy then 1 else 0) +
821 (if p6 = 0uy && p7 = 1uy then 1 else 0) +
822 (if p7 = 0uy && p8 = 1uy then 1 else 0) +
823 (if p8 = 0uy && p9 = 1uy then 1 else 0) +
824 (if p9 = 0uy && p2 = 1uy then 1 else 0) = 1 &&
826 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
827 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
834 oddIteration <- not oddIteration
839 // Remove all 8-connected pixels with an area equal or greater than 'areaSize
'.
840 // Modify 'mat
' in place.
841 let removeArea (mat: Matrix<byte>) (areaSize: int) =
852 use mat' = new Matrix<byte
>(mat.Size)
858 let data' = mat'.Data
862 if data'.[i
, j] = 1uy
864 let neighborhood = List<Point>()
865 let neighborsToCheck = Stack<Point>()
866 neighborsToCheck.Push(Point(j, i
))
869 while neighborsToCheck.Count > 0 do
870 let n = neighborsToCheck.Pop()
872 for (ni, nj) in neighbors do
875 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
877 neighborsToCheck.Push(Point(pj, pi))
878 data'.[pi, pj] <- 0uy
879 if neighborhood.Count <= areaSize
881 for n in neighborhood do
882 data.[n.Y, n.X] <- 0uy
884 let connectedComponents (img: Image<Gray, byte>) (startPoints: List<Point>) : List<Point> =
888 let pointChecked = Points()
889 let pointToCheck = Stack<Point>(startPoints);
893 while pointToCheck.Count > 0 do
894 let next = pointToCheck.Pop()
895 pointChecked.Add(next) |> ignore
898 if ny <> 0 && nx <> 0
900 let p = Point(next.X + nx, next.Y + ny)
901 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)
905 List<Point>(pointChecked)
907 let drawLine (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0
: int) (y0
: int) (x1
: int) (y1
: int) (thickness
: int) =
908 img.Draw(LineSegment2D(Point(x0
, y0
), Point(x1
, y1
)), color
, thickness
);
910 let drawLineF (img: Image<'TColor, 'TDepth>) (color
: 'TColor) (x0: float) (y0: float) (x1: float) (y1: float) (thickness: int) =
911 img.Draw(LineSegment2DF(PointF(float32 x0, float32 y0), PointF(float32 x1, float32 y1)), color, thickness, CvEnum.LineType.AntiAlias);
913 let drawEllipse (img: Image<'TColor, 'TDepth>) (e: Types.Ellipse) (color: 'TColor) (alpha
: float) =
916 img.Draw(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)
918 let windowPosX = e
.Cx - e
.A - 5.f
919 let gapX = windowPosX - (float32
(int windowPosX))
921 let windowPosY = e
.Cy - e
.A - 5.f
922 let gapY = windowPosY - (float32
(int windowPosY))
924 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e
.A + 5.f) |> int, 2.f * (e
.A + 5.f) |> int)
927 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
929 use i = new Image<'TColor, 'TDepth>(img.ROI.Size)
930 i.Draw(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)
931 CvInvoke.AddWeighted(img, 1.0, i, alpha
, 0.0, img)
932 img.ROI <- Rectangle.Empty
934 let drawEllipses (img: Image<'TColor, 'TDepth>) (ellipses
: Types.Ellipse list) (color
: 'TColor) (alpha: float) =
935 List.iter (fun e -> drawEllipse img e color alpha) ellipses
937 let rngCell = System.Random()
938 let drawCell (img: Image<Bgr, byte>) (drawCellContent: bool) (c: Types.Cell) =
941 let colorB = rngCell.Next(20, 70)
942 let colorG = rngCell.Next(20, 70)
943 let colorR = rngCell.Next(20, 70)
945 for y in 0 .. c.elements.Height - 1 do
946 for x in 0 .. c.elements.Width - 1 do
947 if c.elements.[y, x] > 0uy
949 let dx, dy = c.center.X - c.elements.Width / 2, c.center.Y - c.elements.Height / 2
950 let b = img.Data.[y + dy, x + dx, 0] |> int
951 let g = img.Data.[y + dy, x + dx, 1] |> int
952 let r = img.Data.[y + dy, x + dx, 2] |> int
953 img.Data.[y + dy, x + dx, 0] <- if b + colorB > 255 then 255uy else byte (b + colorB)
954 img.Data.[y + dy, x + dx, 1] <- if g + colorG > 255 then 255uy else byte (g + colorG)
955 img.Data.[y + dy, x + dx, 2] <- if r + colorR > 255 then 255uy else byte (r + colorR)
957 let crossColor, crossColor2 =
958 match c.cellClass with
959 | Types.HealthyRBC -> Bgr(255., 0., 0.), Bgr(255., 255., 255.)
960 | Types.InfectedRBC -> Bgr(0., 0., 255.), Bgr(120., 120., 255.)
961 | Types.Peculiar -> Bgr(0., 0., 0.), Bgr(80., 80., 80.)
963 drawLine img crossColor2 (c.center.X - 3) c.center.Y (c.center.X + 3) c.center.Y 2
964 drawLine img crossColor2 c.center.X (c.center.Y - 3) c.center.X (c.center.Y + 3) 2
966 drawLine img crossColor (c.center.X - 3) c.center.Y (c.center.X + 3) c.center.Y 1
967 drawLine img crossColor c.center.X (c.center.Y - 3) c.center.X (c.center.Y + 3) 1
970 let drawCells (img: Image<Bgr, byte>) (drawCellContent: bool) (cells: Types.Cell list) =
971 List.iter (fun c -> drawCell img drawCellContent c) cells