cc15af7f43df9c17744b8ce381570f07a23a29a3
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 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 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 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 use magnitudesByte = magnitudes.Convert<byte>()
205 let threshold, _, _ = otsu (histogramMat magnitudes 300)
206 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
208 // Non-maximum suppression.
209 use nms = new Matrix<byte>(xGradient.Size)
211 let nmsData = nms.Data
212 let anglesData = angles.Data
213 let magnitudesData = magnitudes.Data
214 let xGradientData = xGradient.Data
215 let yGradientData = yGradient.Data
217 for i in 0 .. h - 1 do
218 nmsData.[i, 0] <- 0uy
219 nmsData.[i, w - 1] <- 0uy
221 for j in 0 .. w - 1 do
222 nmsData.[0, j] <- 0uy
223 nmsData.[h - 1, j] <- 0uy
225 for i in 1 .. h - 2 do
226 for j in 1 .. w - 2 do
227 let vx = xGradientData.[i, j, 0]
228 let vy = yGradientData.[i, j, 0]
229 if vx <> 0.f || vy <> 0.f
231 let angle = anglesData.[i, j]
233 let vx', vy' = abs vx, abs vy
234 let ratio2 = if vx' > vy' then vy' / vx' else vx' / vy'
235 let ratio1 = 1.f - ratio2
237 let mNeigbors (sign: int) : float32 =
239 then ratio1 * magnitudesData.[i, j + sign] + ratio2 * magnitudesData.[i + sign, j + sign]
240 elif angle < PI / 2.f
241 then ratio2 * magnitudesData.[i + sign, j + sign] + ratio1 * magnitudesData.[i + sign, j]
242 elif angle < 3.f * PI / 4.f
243 then ratio1 * magnitudesData.[i + sign, j] + ratio2 * magnitudesData.[i + sign, j - sign]
245 then ratio2 * magnitudesData.[i + sign, j - sign] + ratio1 * magnitudesData.[i, j - sign]
246 elif angle < 5.f * PI / 4.f
247 then ratio1 * magnitudesData.[i, j - sign] + ratio2 * magnitudesData.[i - sign, j - sign]
248 elif angle < 3.f * PI / 2.f
249 then ratio2 * magnitudesData.[i - sign, j - sign] + ratio1 * magnitudesData.[i - sign, j]
250 elif angle < 7.f * PI / 4.f
251 then ratio1 * magnitudesData.[i - sign, j] + ratio2 * magnitudesData.[i - sign, j + sign]
252 else ratio2 * magnitudesData.[i - sign, j + sign] + ratio1 * magnitudesData.[i, j + sign]
254 let m = magnitudesData.[i, j]
255 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
257 nmsData.[i, j] <- 1uy
259 // suppressMConnections nms // It's
not helpful
for the rest of the process (ellipse
detection).
261 let edges = new Matrix<byte
>(xGradient.Size)
262 let edgesData = edges.Data
264 // Hysteresis thresholding.
265 let toVisit = Stack<Point>()
266 for i
in 0 .. h - 1 do
267 for j
in 0 .. w - 1 do
268 if nmsData.[i
, j
] = 1uy && magnitudesData.[i
, j
] >= thresholdHigh
270 nmsData.[i
, j
] <- 0uy
271 toVisit.Push(Point(j
, i
))
272 while toVisit.Count > 0 do
273 let p = toVisit.Pop()
274 edgesData.[p.Y, p.X] <- 1uy
277 if i
' <> 0 || j' <> 0
281 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
283 nmsData.[ni, nj] <- 0uy
284 toVisit.Push(Point(nj, ni))
286 edges, xGradient, yGradient
288 let gaussianFilter (img : Image<'TColor, 'TDepth>) (standardDeviation
: float) : Image<'TColor, 'TDepth> =
289 let size = 2 * int (ceil
(4.0 * standardDeviation
)) + 1
290 img.SmoothGaussian(size, size, standardDeviation
, standardDeviation
)
292 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
294 img.Data.[p.Y, p.X, 0] <- intensity
300 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
303 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
305 let imgData = img.Data
306 let suppress: bool[,] = Array2D.zeroCreate h w
308 let result = List<List<Point>>()
310 let flood (start: Point) : List<List<Point>> =
311 let sameLevelToCheck = Stack<Point>()
312 let betterLevelToCheck = Stack<Point>()
313 betterLevelToCheck.Push(start)
315 let result' = List<List<Point>>()
317 while betterLevelToCheck.Count > 0 do
318 let p = betterLevelToCheck.Pop()
319 if not suppress.[p.Y, p.X]
321 suppress.[p.Y, p.X] <- true
322 sameLevelToCheck.Push(p)
323 let current = List<Point>()
325 let mutable betterExists = false
327 while sameLevelToCheck.Count > 0 do
328 let p' = sameLevelToCheck.Pop()
329 let currentLevel = imgData.[p'.Y, p'.X, 0]
330 current.Add(p') |> ignore
334 if ni >= 0 && ni < h && nj >= 0 && nj < w
336 let level = imgData.[ni, nj, 0]
337 let notSuppressed = not suppress.[ni, nj]
339 if level = currentLevel && notSuppressed
341 suppress.[ni, nj] <- true
342 sameLevelToCheck.Push(Point(nj, ni))
343 elif
if extremumType
= ExtremumType.Maxima then level > currentLevel else level < currentLevel
348 betterLevelToCheck.Push(Point(nj, ni))
355 for i
in 0 .. h - 1 do
356 for j in 0 .. w - 1 do
357 let maxima = flood (Point(j, i
))
360 result.AddRange(maxima)
362 result.Select(fun l
-> Points(l
))
364 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
365 findExtremum img ExtremumType.Maxima
367 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
368 findExtremum img ExtremumType.Minima
370 type PriorityQueue () =
372 let q: Points[] = Array.init
size (fun i
-> Points())
373 let mutable highest = -1 // Value of the first elements of 'q'.
374 let mutable lowest = size
376 member this
.NextMax () : byte
* Point =
379 invalidOp
"Queue is empty"
383 l.Remove(next) |> ignore
384 let value = byte
highest
388 highest <- highest - 1
389 while highest > lowest && q.[highest].Count = 0 do
390 highest <- highest - 1
398 member this
.NextMin () : byte
* Point =
401 invalidOp
"Queue is empty"
403 let l = q.[lowest + 1]
405 l.Remove(next) |> ignore
406 let value = byte
(lowest + 1)
411 while lowest < highest && q.[lowest + 1].Count = 0 do
426 member this
.Add (value: byte
) (p: Point) =
436 q.[vi].Add(p) |> ignore
438 member this
.Remove (value: byte
) (p: Point) =
440 if q.[vi].Remove(p) && q.[vi].Count = 0
444 highest <- highest - 1
445 while highest > lowest && q.[highest].Count = 0 do
446 highest <- highest - 1
450 while lowest < highest && q.[lowest + 1].Count = 0 do
453 if highest = lowest // The queue is now empty.
458 member this
.IsEmpty =
461 member this
.Clear () =
462 while highest > lowest do
464 highest <- highest - 1
468 type private AreaState =
473 type private AreaOperation =
478 type private Area (elements
: Points) =
479 member this
.Elements = elements
480 member val Intensity = None with get
, set
481 member val State = AreaState.Unprocessed with get
, set
483 let private areaOperation
(img: Image<Gray, byte
>) (area
: int) (op
: AreaOperation) =
486 let imgData = img.Data
487 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
489 let areas = List<Area>((if op
= AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map
Area)
491 let pixels: Area[,] = Array2D.create
h w null
493 for e
in m.Elements do
494 pixels.[e
.Y, e
.X] <- m
496 let queue = PriorityQueue()
498 let addEdgeToQueue (elements
: Points) =
503 let p' = Point(nj, ni)
504 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
506 queue.Add (imgData.[ni, nj, 0]) p'
508 // Reverse order is quicker.
509 for i in areas.Count - 1 .. -1 .. 0 do
511 if m.Elements.Count <= area && m.State <> AreaState.Removed
514 addEdgeToQueue m.Elements
516 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
517 let nextElements = Points()
519 let mutable stop = false
521 let intensity', p = if op
= AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
522 let mutable merged = false
524 if intensity' = intensity // The intensity doesn't
change.
526 if m.Elements.Count + nextElements.Count + 1 > area
528 m.State <- AreaState.Validated
529 m.Intensity <- Some intensity
532 nextElements.Add(p) |> ignore
534 elif
if op
= AreaOperation.Opening then intensity' < intensity else intensity' > intensity
536 m.Elements.UnionWith(nextElements)
537 for e
in nextElements do
538 pixels.[e
.Y, e
.X] <- m
540 if m.Elements.Count = area
542 m.State <- AreaState.Validated
543 m.Intensity <- Some (intensity')
546 intensity <- intensity'
548 nextElements.Add(p) |> ignore
551 match pixels.[p.Y, p.X] with
554 if m'.Elements.Count + m.Elements.Count <= area
556 m'.State <- AreaState.Removed
557 for e in m'.Elements do
558 pixels.[e
.Y, e
.X] <- m
559 queue.Remove imgData.[e
.Y, e
.X, 0] e
560 addEdgeToQueue m'.Elements
561 m.Elements.UnionWith(m'.Elements)
562 let intensityMax = if op
= AreaOperation.Opening then queue.Max else queue.Min
563 if intensityMax <> intensity
565 intensity <- intensityMax
571 m.State <- AreaState.Validated
572 m.Intensity <- Some (intensity)
575 if not stop && not merged
580 let p' = Point(nj, ni)
581 if ni < 0 || ni >= h || nj < 0 || nj >= w
583 m.State <- AreaState.Validated
584 m.Intensity <- Some (intensity)
586 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
588 queue.Add (imgData.[ni, nj, 0]) p'
592 if m.Elements.Count + nextElements.Count <= area
594 m.State <- AreaState.Validated
595 m.Intensity <- Some intensity'
596 m.Elements.UnionWith(nextElements)
600 if m.State = AreaState.Validated
602 match m.Intensity with
604 for p in m.Elements do
605 imgData.[p.Y, p.X, 0] <- i
610 /// Area opening on byte image.
612 let areaOpen (img: Image<Gray, byte>) (area: int) =
613 areaOperation img area AreaOperation.Opening
616 /// Area closing on byte image.
618 let areaClose (img: Image<Gray, byte>) (area: int) =
619 areaOperation img area AreaOperation.Closing
621 // A simpler algorithm than 'areaOpen' on byte image but slower.
622 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
625 let imgData = img.Data
626 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
628 let histogram = Array.zeroCreate 256
629 for i in 0 .. h - 1 do
630 for j in 0 .. w - 1 do
631 let v = imgData.[i, j, 0] |> int
632 histogram.[v] <- histogram.[v] + 1
634 let flooded : bool[,] = Array2D.zeroCreate h w
636 let pointsChecked = HashSet<Point>()
637 let pointsToCheck = Stack<Point>()
639 for level in 255 .. -1 .. 0 do
640 let mutable n = histogram.[level]
643 for i in 0 .. h - 1 do
644 for j in 0 .. w - 1 do
645 if not flooded.[i, j] && imgData.[i, j, 0] = byte level
647 let mutable maxNeighborValue = 0uy
648 pointsChecked.Clear()
649 pointsToCheck.Clear()
650 pointsToCheck.Push(Point(j, i))
652 while pointsToCheck.Count > 0 do
653 let next = pointsToCheck.Pop()
654 pointsChecked.Add(next) |> ignore
655 flooded.[next.Y, next.X] <- true
658 let p = Point(next.X + nx, next.Y + ny)
659 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
661 let v = imgData.[p.Y, p.X, 0]
664 if not (pointsChecked.Contains(p))
666 pointsToCheck.Push(p)
667 elif v > maxNeighborValue
669 maxNeighborValue <- v
671 if int maxNeighborValue < level && pointsChecked.Count <= area
673 for p in pointsChecked do
674 imgData.[p.Y, p.X, 0] <- maxNeighborValue
677 type Island (cmp: IComparer<float32>) =
678 member val Shore = Heap.Heap<float32, Point>(cmp) with get
679 member val Level = 0.f with get, set
680 member val Surface = 0 with get, set
681 member this.IsInfinite = this.Surface = Int32.MaxValue
683 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: ('a -> float32 -> unit) option) (op: AreaOperation) =
687 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
689 let comparer = if op = AreaOperation.Opening
690 then { new IComparer<float32> with member this.Compare(v1, v2) = v1.CompareTo(v2) }
691 else { new IComparer<float32> with member this.Compare(v1, v2) = v2.CompareTo(v1) }
693 let ownership: Island[,] = Array2D.create h w null
695 // Initialize islands with their shore.
696 let islands = List<Island>()
697 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
701 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
703 let shorePoints = Points()
705 ownership.[p.Y, p.X] <- island
709 let neighbor = Point(nj, ni)
710 if ni >= 0 && ni < h && nj >= 0 && nj < w && Object.ReferenceEquals(ownership.[ni, nj], null) && not (shorePoints.Contains(neighbor))
712 shorePoints.Add(neighbor) |> ignore
713 island.Shore.Add earth.[ni, nj, 0] neighbor
715 for area, obj in areas do
716 for island in islands do
717 let mutable stop = island.Shore.IsEmpty
719 // 'true' if 'p' is owned or adjacent to 'island'.
720 let inline ownedOrAdjacent (p: Point) : bool =
721 ownership.[p.Y, p.X] = island ||
722 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
723 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
724 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
725 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
727 while not stop && island.Surface < area do
728 let level, next = island.Shore.Max
729 let other = ownership.[next.Y, next.X]
730 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
732 island.Shore.RemoveNext ()
734 if not <| Object.ReferenceEquals(other, null)
735 then // We touching another island.
736 if island.IsInfinite || other.IsInfinite || island.Surface + other.Surface >= area
739 else // We can merge 'other' into 'surface
'.
740 island.Surface <- island.Surface + other.Surface
741 island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then island.Level else other.Level
742 for l, p in other.Shore do
743 let mutable currentY = p.Y + 1
744 while currentY < h && ownership.[currentY, p.X] = other do
745 ownership.[currentY, p.X] <- island
746 currentY <- currentY + 1
750 elif comparer.Compare(level, island.Level) > 0
754 island.Shore.RemoveNext ()
758 if ni < 0 || ni >= h || nj < 0 || nj >= w
760 island.Surface <- Int32.MaxValue
763 let neighbor = Point(nj, ni)
764 if not <| ownedOrAdjacent neighbor
766 island.Shore.Add earth.[ni, nj, 0] neighbor
769 ownership.[next.Y, next.X] <- island
770 island.Level <- level
771 island.Surface <- island.Surface + 1
773 let mutable diff = 0.f
775 for i in 0 .. h - 1 do
776 for j in 0 .. w - 1 do
777 match ownership.[i, j] with
781 diff <- diff + l - earth.[i, j, 0]
785 | Some f' -> f
' obj diff
790 /// Area opening on float image.
792 let areaOpenF (img: Image<Gray, float32>) (area: int) =
793 areaOperationF img [ area, () ] None AreaOperation.Opening
796 /// Area closing on float image.
798 let areaCloseF (img: Image<Gray, float32>) (area: int) =
799 areaOperationF img [ area, () ] None AreaOperation.Closing
802 /// Area closing on float image with different areas. Given areas must be sorted increasingly.
803 /// For each area the function 'f
' is called with the associated area value of type 'a
and the volume difference
804 /// Between the previous and the current closing.
806 let areaOpenFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
807 areaOperationF
img areas (Some f) AreaOperation.Opening
810 /// Same as 'areaOpenFWithFun' for closing operation.
812 let areaCloseFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
813 areaOperationF
img areas (Some f) AreaOperation.Closing
816 /// Zhang and Suen thinning algorithm.
817 /// Modify 'mat' in place.
819 let thin (mat
: Matrix<byte
>) =
822 let mutable data1 = mat
.Data
823 let mutable data2 = Array2D.copy
data1
825 let mutable pixelChanged = true
826 let mutable oddIteration = true
828 while pixelChanged do
829 pixelChanged <- false
832 if data1.[i
, j] = 1uy
834 let p2 = if i
= 0 then 0uy else data1.[i
-1, j]
835 let p3 = if i
= 0 || j = w-1 then 0uy else data1.[i
-1, j+1]
836 let p4 = if j = w-1 then 0uy else data1.[i
, j+1]
837 let p5 = if i
= h-1 || j = w-1 then 0uy else data1.[i
+1, j+1]
838 let p6 = if i
= h-1 then 0uy else data1.[i
+1, j]
839 let p7 = if i
= h-1 || j = 0 then 0uy else data1.[i
+1, j-1]
840 let p8 = if j = 0 then 0uy else data1.[i
, j-1]
841 let p9 = if i
= 0 || j = 0 then 0uy else data1.[i
-1, j-1]
843 let sumNeighbors = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
844 if sumNeighbors >= 2uy && sumNeighbors <= 6uy &&
845 (if p2 = 0uy && p3 = 1uy then 1 else 0) +
846 (if p3 = 0uy && p4 = 1uy then 1 else 0) +
847 (if p4 = 0uy && p5 = 1uy then 1 else 0) +
848 (if p5 = 0uy && p6 = 1uy then 1 else 0) +
849 (if p6 = 0uy && p7 = 1uy then 1 else 0) +
850 (if p7 = 0uy && p8 = 1uy then 1 else 0) +
851 (if p8 = 0uy && p9 = 1uy then 1 else 0) +
852 (if p9 = 0uy && p2 = 1uy then 1 else 0) = 1 &&
854 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
855 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
862 oddIteration <- not oddIteration
868 /// Remove all 8-connected pixels with an area equal or greater than 'areaSize'.
869 /// Modify 'mat' in place.
871 let removeArea (mat
: Matrix<byte
>) (areaSize
: int) =
882 use mat' = new Matrix<byte>(mat.Size)
888 let data' = mat'.Data
892 if data'.[i, j] = 1uy
894 let neighborhood = List<Point>()
895 let neighborsToCheck = Stack<Point>()
896 neighborsToCheck.Push(Point(j, i))
899 while neighborsToCheck.Count > 0 do
900 let n = neighborsToCheck.Pop()
902 for (ni, nj) in neighbors do
905 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
907 neighborsToCheck.Push(Point(pj, pi))
908 data'.[pi, pj] <- 0uy
909 if neighborhood.Count <= areaSize
911 for n in neighborhood do
912 data.[n.Y, n.X] <- 0uy
914 let connectedComponents (img: Image<Gray, byte
>) (startPoints
: List<Point>) : Points =
918 let pointChecked = Points()
919 let pointToCheck = Stack<Point>(startPoints
);
923 while pointToCheck.Count > 0 do
924 let next = pointToCheck.Pop()
925 pointChecked.Add(next) |> ignore
928 if ny
<> 0 && nx
<> 0
930 let p = Point(next.X + nx
, next.Y + ny
)
931 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)
937 let drawLine (img: Image<'TColor, 'TDepth>) (color
: 'TColor) (x0: int) (y0: int) (x1: int) (y1: int) (thickness: int) =
938 img.Draw(LineSegment2D(Point(x0, y0), Point(x1, y1)), color, thickness);
940 let drawLineF (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0
: float) (y0
: float) (x1
: float) (y1
: float) (thickness
: int) =
941 img.Draw(LineSegment2DF(PointF(float32 x0
, float32 y0
), PointF(float32 x1
, float32 y1
)), color
, thickness
, CvEnum.LineType.AntiAlias);
943 let drawEllipse (img: Image<'TColor, 'TDepth>) (e
: Ellipse) (color
: 'TColor) (alpha: float) =
946 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)
948 let windowPosX = e.Cx - e.A - 5.f
949 let gapX = windowPosX - (float32 (int windowPosX))
951 let windowPosY = e.Cy - e.A - 5.f
952 let gapY = windowPosY - (float32 (int windowPosY))
954 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e.A + 5.f) |> int, 2.f * (e.A + 5.f) |> int)
957 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
959 use i = new Image<'TColor, 'TDepth>(img.ROI.Size)
960 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)
961 CvInvoke.AddWeighted(img, 1.0, i, alpha, 0.0, img)
962 img.ROI <- Rectangle.Empty
964 let drawEllipses (img: Image<'TColor, 'TDepth>) (ellipses: Ellipse list) (color: 'TColor) (alpha
: float) =
965 List.iter
(fun e
-> drawEllipse img e
color alpha
) ellipses
967 let rngCell = System.Random()
968 let drawCell (img: Image<Bgr, byte
>) (drawCellContent
: bool) (c
: Cell) =
971 let colorB = rngCell.Next(20, 70)
972 let colorG = rngCell.Next(20, 70)
973 let colorR = rngCell.Next(20, 70)
975 for y
in 0 .. c
.elements
.Height - 1 do
976 for x
in 0 .. c
.elements
.Width - 1 do
977 if c
.elements
.[y
, x
] > 0uy
979 let dx, dy
= c
.center
.X - c
.elements
.Width / 2, c
.center
.Y - c
.elements
.Height / 2
980 let b = img.Data.[y
+ dy
, x
+ dx, 0] |> int
981 let g = img.Data.[y
+ dy
, x
+ dx, 1] |> int
982 let r = img.Data.[y
+ dy
, x
+ dx, 2] |> int
983 img.Data.[y
+ dy
, x
+ dx, 0] <- if b + colorB > 255 then 255uy else byte (b + colorB)
984 img.Data.[y
+ dy
, x
+ dx, 1] <- if g + colorG > 255 then 255uy else byte (g + colorG)
985 img.Data.[y
+ dy
, x
+ dx, 2] <- if r + colorR > 255 then 255uy else byte (r + colorR)
987 let crossColor, crossColor2
=
988 match c
.cellClass
with
989 | HealthyRBC -> Bgr(255., 0., 0.), Bgr(255., 255., 255.)
990 | InfectedRBC -> Bgr(0., 0., 255.), Bgr(120., 120., 255.)
991 | Peculiar -> Bgr(0., 0., 0.), Bgr(80., 80., 80.)
993 drawLine img crossColor2
(c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 2
994 drawLine img crossColor2 c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 2
996 drawLine img crossColor (c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 1
997 drawLine img crossColor c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 1
1000 let drawCells (img: Image<Bgr, byte>) (drawCellContent
: bool) (cells
: Cell list) =
1001 List.iter
(fun c
-> drawCell img drawCellContent
c) cells