096fd94ec7e9736cd73a60200ce95be017ca6c35
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>()
25 let saveImg (img: Image<'TColor, 'TDepth>) (filepath: string) =
29 let saveMat (mat: Matrix<'TDepth>) (filepath
: string) =
30 use img = new Image<Gray, 'TDeph>(mat.Size)
34 type Histogram = { data: int[]; total: int; sum: int; min: float32; max: float32 }
36 let histogramImg (img: Image<Gray, float32>) (nbSamples: int) : Histogram =
37 let imgData = img.Data
40 let min = ref [| 0.0 |]
41 let minLocation = ref <| [| Point() |]
42 let max = ref [| 0.0 |]
43 let maxLocation = ref <| [| Point() |]
44 img.MinMax(min, max, minLocation, maxLocation)
45 float32 (!min).[0], float32 (!max).[0]
47 let bin (x: float32) : int =
48 let p = int ((x - min) / (max - min) * float32 nbSamples)
49 if p >= nbSamples then nbSamples - 1 else p
51 let data = Array.zeroCreate nbSamples
53 for i in 0 .. img.Height - 1 do
54 for j in 0 .. img.Width - 1 do
55 let p = bin imgData.[i, j, 0]
56 data.[p] <- data.[p] + 1
58 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
60 let histogramMat (mat: Matrix<float32>) (nbSamples: int) : Histogram =
61 let matData = mat.Data
65 let minLocation = ref <| Point()
67 let maxLocation = ref <| Point()
68 mat.MinMax(min, max, minLocation, maxLocation)
69 float32 !min, float32 !max
71 let bin (x: float32) : int =
72 let p = int ((x - min) / (max - min) * float32 nbSamples)
73 if p >= nbSamples then nbSamples - 1 else p
75 let data = Array.zeroCreate nbSamples
77 for i in 0 .. mat.Height - 1 do
78 for j in 0 .. mat.Width - 1 do
79 let p = bin matData.[i, j]
80 data.[p] <- data.[p] + 1
82 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
84 let histogram (values: float32 seq) (nbSamples: int) : Histogram =
85 let mutable min = Single.MaxValue
86 let mutable max = Single.MinValue
91 if v < min then min <- v
92 if v > max then max <- v
94 let bin (x: float32) : int =
95 let p = int ((x - min) / (max - min) * float32 nbSamples)
96 if p >= nbSamples then nbSamples - 1 else p
98 let data = Array.zeroCreate nbSamples
102 data.[p] <- data.[p] + 1
104 { data = data; total = n; sum = Array.sum data; min = min; max = max }
106 let otsu (hist: Histogram) : float32 * float32 * float32 =
109 let mutable maximum = 0.0
110 let mutable level = 0
111 let sum = hist.data |> Array.mapi (fun i v -> i * v) |> Array.sum |> float
113 for i in 0 .. hist.data.Length - 1 do
114 wB <- wB + hist.data.[i]
117 let wF = hist.total - wB
120 sumB <- sumB + i * hist.data.[i]
121 let mB = (float sumB) / (float wB)
122 let mF = (sum - float sumB) / (float wF)
123 let between = (float wB) * (float wF) * (mB - mF) ** 2.;
124 if between >= maximum
132 for i in 0 .. level - 1 do
133 sum <- sum + i * hist.data.[i]
134 nb <- nb + hist.data.[i]
135 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
140 for i in level + 1 .. hist.data.Length - 1 do
141 sum <- sum + i * hist.data.[i]
142 nb <- nb + hist.data.[i]
143 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
146 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
148 toFloat level, toFloat mean1, toFloat mean2
150 let suppressMConnections (img: Matrix<byte>) =
153 for i in 1 .. h - 2 do
154 for j in 1 .. w - 2 do
155 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)
158 for i in 1 .. h - 2 do
159 for j in 1 .. w - 2 do
160 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)
164 let findEdges (img: Image<Gray, float32>) : Matrix<byte> * Image<Gray, float32> * Image<Gray, float32> =
169 new ConvolutionKernelF(array2D [[ 1.0f; 0.0f; -1.0f ]
170 [ 2.0f; 0.0f; -2.0f ]
171 [ 1.0f; 0.0f; -1.0f ]], Point(1, 1))
173 let xGradient = img.Convolution(sobelKernel)
174 let yGradient = img.Convolution(sobelKernel.Transpose())
176 let xGradientData = xGradient.Data
177 let yGradientData = yGradient.Data
178 for r in 0 .. h - 1 do
179 xGradientData.[r, 0, 0] <- 0.f
180 xGradientData.[r, w - 1, 0] <- 0.f
181 yGradientData.[r, 0, 0] <- 0.f
182 yGradientData.[r, w - 1, 0] <- 0.f
184 for c in 0 .. w - 1 do
185 xGradientData.[0, c, 0] <- 0.f
186 xGradientData.[h - 1, c, 0] <- 0.f
187 yGradientData.[0, c, 0] <- 0.f
188 yGradientData.[h - 1, c, 0] <- 0.f
190 use magnitudes = new Matrix<float32>(xGradient.Size)
191 use angles = new Matrix<float32>(xGradient.Size)
192 CvInvoke.CartToPolar(xGradient, yGradient, magnitudes, angles) // Compute the magnitudes (without angles).
194 let thresholdHigh, thresholdLow =
195 let sensibilityHigh = 0.1f
196 let sensibilityLow = 0.0f
197 use magnitudesByte = magnitudes.Convert<byte>()
198 let threshold, _, _ = otsu (histogramMat magnitudes 300)
199 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
201 // Non-maximum suppression.
202 use nms = new Matrix<byte>(xGradient.Size)
204 let nmsData = nms.Data
205 let anglesData = angles.Data
206 let magnitudesData = magnitudes.Data
207 let xGradientData = xGradient.Data
208 let yGradientData = yGradient.Data
210 let PI = float32 Math.PI
212 for i in 0 .. h - 1 do
213 nmsData.[i, 0] <- 0uy
214 nmsData.[i, w - 1] <- 0uy
216 for j in 0 .. w - 1 do
217 nmsData.[0, j] <- 0uy
218 nmsData.[h - 1, j] <- 0uy
220 for i in 1 .. h - 2 do
221 for j in 1 .. w - 2 do
222 let vx = xGradientData.[i, j, 0]
223 let vy = yGradientData.[i, j, 0]
224 if vx <> 0.f || vy <> 0.f
226 let angle = anglesData.[i, j]
228 let vx', vy' = abs vx, abs vy
229 let ratio2 = if vx' > vy' then vy' / vx' else vx' / vy'
230 let ratio1 = 1.f - ratio2
232 let mNeigbors (sign: int) : float32 =
234 then ratio1 * magnitudesData.[i, j + sign] + ratio2 * magnitudesData.[i + sign, j + sign]
235 elif angle < PI / 2.f
236 then ratio2 * magnitudesData.[i + sign, j + sign] + ratio1 * magnitudesData.[i + sign, j]
237 elif angle < 3.f * PI / 4.f
238 then ratio1 * magnitudesData.[i + sign, j] + ratio2 * magnitudesData.[i + sign, j - sign]
240 then ratio2 * magnitudesData.[i + sign, j - sign] + ratio1 * magnitudesData.[i, j - sign]
241 elif angle < 5.f * PI / 4.f
242 then ratio1 * magnitudesData.[i, j - sign] + ratio2 * magnitudesData.[i - sign, j - sign]
243 elif angle < 3.f * PI / 2.f
244 then ratio2 * magnitudesData.[i - sign, j - sign] + ratio1 * magnitudesData.[i - sign, j]
245 elif angle < 7.f * PI / 4.f
246 then ratio1 * magnitudesData.[i - sign, j] + ratio2 * magnitudesData.[i - sign, j + sign]
247 else ratio2 * magnitudesData.[i - sign, j + sign] + ratio1 * magnitudesData.[i, j + sign]
249 let m = magnitudesData.[i, j]
250 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
252 nmsData.[i, j] <- 1uy
254 // suppressMConnections nms // It's
not helpful
for the rest of the process (ellipse
detection).
256 let edges = new Matrix<byte
>(xGradient.Size)
257 let edgesData = edges.Data
259 // Hysteresis thresholding.
260 let toVisit = Stack<Point>()
261 for i
in 0 .. h - 1 do
262 for j
in 0 .. w - 1 do
263 if nmsData.[i
, j
] = 1uy && magnitudesData.[i
, j
] >= thresholdHigh
265 nmsData.[i
, j
] <- 0uy
266 toVisit.Push(Point(j
, i
))
267 while toVisit.Count > 0 do
268 let p = toVisit.Pop()
269 edgesData.[p.Y, p.X] <- 1uy
272 if i
' <> 0 || j' <> 0
276 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
278 nmsData.[ni, nj] <- 0uy
279 toVisit.Push(Point(nj, ni))
281 edges, xGradient, yGradient
283 let gaussianFilter (img : Image<'TColor, 'TDepth>) (standardDeviation
: float) : Image<'TColor, 'TDepth> =
284 let size = 2 * int (ceil
(4.0 * standardDeviation
)) + 1
285 img.SmoothGaussian(size, size, standardDeviation
, standardDeviation
)
287 type Points = HashSet<Point>
289 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
291 img.Data.[p.Y, p.X, 0] <- intensity
297 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
300 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
302 let imgData = img.Data
303 let suppress: bool[,] = Array2D.zeroCreate h w
305 let result = List<List<Point>>()
307 let flood (start: Point) : List<List<Point>> =
308 let sameLevelToCheck = Stack<Point>()
309 let betterLevelToCheck = Stack<Point>()
310 betterLevelToCheck.Push(start)
312 let result' = List<List<Point>>()
314 while betterLevelToCheck.Count > 0 do
315 let p = betterLevelToCheck.Pop()
316 if not suppress.[p.Y, p.X]
318 suppress.[p.Y, p.X] <- true
319 sameLevelToCheck.Push(p)
320 let current = List<Point>()
322 let mutable betterExists = false
324 while sameLevelToCheck.Count > 0 do
325 let p' = sameLevelToCheck.Pop()
326 let currentLevel = imgData.[p'.Y, p'.X, 0]
327 current.Add(p') |> ignore
331 if ni >= 0 && ni < h && nj >= 0 && nj < w
333 let level = imgData.[ni, nj, 0]
334 let notSuppressed = not suppress.[ni, nj]
336 if level = currentLevel && notSuppressed
338 suppress.[ni, nj] <- true
339 sameLevelToCheck.Push(Point(nj, ni))
340 elif
if extremumType
= ExtremumType.Maxima then level > currentLevel else level < currentLevel
345 betterLevelToCheck.Push(Point(nj, ni))
352 for i
in 0 .. h - 1 do
353 for j in 0 .. w - 1 do
354 let maxima = flood (Point(j, i
))
357 result.AddRange(maxima)
359 result.Select(fun l
-> Points(l
))
361 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
362 findExtremum img ExtremumType.Maxima
364 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
365 findExtremum img ExtremumType.Minima
367 type PriorityQueue () =
369 let q: Points[] = Array.init
size (fun i
-> Points())
370 let mutable highest = -1 // Value of the first elements of 'q'.
371 let mutable lowest = size
373 member this
.NextMax () : byte
* Point =
376 invalidOp
"Queue is empty"
380 l.Remove(next) |> ignore
381 let value = byte
highest
385 highest <- highest - 1
386 while highest > lowest && q.[highest].Count = 0 do
387 highest <- highest - 1
395 member this
.NextMin () : byte
* Point =
398 invalidOp
"Queue is empty"
400 let l = q.[lowest + 1]
402 l.Remove(next) |> ignore
403 let value = byte
(lowest + 1)
408 while lowest < highest && q.[lowest + 1].Count = 0 do
423 member this
.Add (value: byte
) (p: Point) =
433 q.[vi].Add(p) |> ignore
435 member this
.Remove (value: byte
) (p: Point) =
437 if q.[vi].Remove(p) && q.[vi].Count = 0
441 highest <- highest - 1
442 while highest > lowest && q.[highest].Count = 0 do
443 highest <- highest - 1
447 while lowest < highest && q.[lowest + 1].Count = 0 do
450 if highest = lowest // The queue is now empty.
455 member this
.IsEmpty =
458 member this
.Clear () =
459 while highest > lowest do
461 highest <- highest - 1
465 type private AreaState =
470 type private AreaOperation =
475 type private Area (elements
: Points) =
476 member this
.Elements = elements
477 member val Intensity = None with get
, set
478 member val State = AreaState.Unprocessed with get
, set
480 let private areaOperation
(img: Image<Gray, byte
>) (area
: int) (op
: AreaOperation) =
483 let imgData = img.Data
484 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
486 let areas = List<Area>((if op
= AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map
Area)
488 let pixels: Area[,] = Array2D.create
h w null
490 for e
in m.Elements do
491 pixels.[e
.Y, e
.X] <- m
493 let queue = PriorityQueue()
495 let addEdgeToQueue (elements
: Points) =
500 let p' = Point(nj, ni)
501 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
503 queue.Add (imgData.[ni, nj, 0]) p'
505 // Reverse order is quicker.
506 for i in areas.Count - 1 .. -1 .. 0 do
508 if m.Elements.Count <= area && m.State <> AreaState.Removed
511 addEdgeToQueue m.Elements
513 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
514 let nextElements = Points()
516 let mutable stop = false
518 let intensity', p = if op
= AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
519 let mutable merged = false
521 if intensity' = intensity // The intensity doesn't
change.
523 if m.Elements.Count + nextElements.Count + 1 > area
525 m.State <- AreaState.Validated
526 m.Intensity <- Some intensity
529 nextElements.Add(p) |> ignore
531 elif
if op
= AreaOperation.Opening then intensity' < intensity else intensity' > intensity
533 m.Elements.UnionWith(nextElements)
534 for e
in nextElements do
535 pixels.[e
.Y, e
.X] <- m
537 if m.Elements.Count = area
539 m.State <- AreaState.Validated
540 m.Intensity <- Some (intensity')
543 intensity <- intensity'
545 nextElements.Add(p) |> ignore
548 match pixels.[p.Y, p.X] with
551 if m'.Elements.Count + m.Elements.Count <= area
553 m'.State <- AreaState.Removed
554 for e in m'.Elements do
555 pixels.[e
.Y, e
.X] <- m
556 queue.Remove imgData.[e
.Y, e
.X, 0] e
557 addEdgeToQueue m'.Elements
558 m.Elements.UnionWith(m'.Elements)
559 let intensityMax = if op
= AreaOperation.Opening then queue.Max else queue.Min
560 if intensityMax <> intensity
562 intensity <- intensityMax
568 m.State <- AreaState.Validated
569 m.Intensity <- Some (intensity)
572 if not stop && not merged
577 let p' = Point(nj, ni)
578 if ni < 0 || ni >= h || nj < 0 || nj >= w
580 m.State <- AreaState.Validated
581 m.Intensity <- Some (intensity)
583 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
585 queue.Add (imgData.[ni, nj, 0]) p'
589 if m.Elements.Count + nextElements.Count <= area
591 m.State <- AreaState.Validated
592 m.Intensity <- Some intensity'
593 m.Elements.UnionWith(nextElements)
597 if m.State = AreaState.Validated
599 match m.Intensity with
601 for p in m.Elements do
602 imgData.[p.Y, p.X, 0] <- i
606 let areaOpen (img: Image<Gray, byte>) (area: int) =
607 areaOperation img area AreaOperation.Opening
609 let areaClose (img: Image<Gray, byte>) (area: int) =
610 areaOperation img area AreaOperation.Closing
613 type Island (cmp: IComparer<float32>) =
614 member val Shore = Heap.Heap<float32, Point>(cmp) with get
615 member val Level = 0.f with get, set
616 member val Surface = 0 with get, set
618 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: ('a -> float32 -> unit) option) (op: AreaOperation) =
622 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
624 let comparer = if op = AreaOperation.Opening
625 then { new IComparer<float32> with member this.Compare(v1, v2) = v1.CompareTo(v2) }
626 else { new IComparer<float32> with member this.Compare(v1, v2) = v2.CompareTo(v1) }
628 let ownership: Island[,] = Array2D.create h w null
630 // Initialize islands with their shore.
631 let islands = List<Island>()
632 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
636 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
638 let shorePoints = Points()
640 ownership.[p.Y, p.X] <- island
644 let neighbor = Point(nj, ni)
645 if ni >= 0 && ni < h && nj >= 0 && nj < w && Object.ReferenceEquals(ownership.[ni, nj], null) && not (shorePoints.Contains(neighbor))
647 shorePoints.Add(neighbor) |> ignore
648 island.Shore.Add earth.[ni, nj, 0] neighbor
650 for area, obj in areas do
651 for island in islands do
652 let mutable stop = island.Shore.IsEmpty
654 // 'true' if 'p' is owned or adjacent to 'island'.
655 let inline ownedOrAdjacent (p: Point) : bool =
656 ownership.[p.Y, p.X] = island ||
657 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
658 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
659 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
660 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
662 while not stop && island.Surface < area do
663 let level, next = island.Shore.Max
664 let other = ownership.[next.Y, next.X]
665 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
667 island.Shore.RemoveNext ()
669 if not <| Object.ReferenceEquals(other, null)
670 then // We touching another island.
671 if island.Surface + other.Surface >= area
674 else // We can merge 'other' into 'surface
'.
675 island.Surface <- island.Surface + other.Surface
676 island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then island.Level else other.Level
677 for l, p in other.Shore do
678 let mutable currentY = p.Y + 1
679 while currentY < h && ownership.[currentY, p.X] = other do
680 ownership.[currentY, p.X] <- island
681 currentY <- currentY + 1
685 elif comparer.Compare(level, island.Level) > 0
689 island.Shore.RemoveNext ()
693 if ni < 0 || ni >= h || nj < 0 || nj >= w
695 island.Surface <- Int32.MaxValue
698 let neighbor = Point(nj, ni)
699 if not <| ownedOrAdjacent neighbor
701 island.Shore.Add earth.[ni, nj, 0] neighbor
704 ownership.[next.Y, next.X] <- island
705 island.Level <- level
706 island.Surface <- island.Surface + 1
708 let mutable diff = 0.f
710 for i in 0 .. h - 1 do
711 for j in 0 .. w - 1 do
712 match ownership.[i, j] with
716 diff <- diff + l - earth.[i, j, 0]
720 | Some f' -> f
' obj diff
724 let areaOpenF (img: Image<Gray, float32>) (area: int) =
725 areaOperationF img [ area, () ] None AreaOperation.Opening
727 let areaCloseF (img: Image<Gray, float32>) (area: int) =
728 areaOperationF img [ area, () ] None AreaOperation.Closing
730 let areaOpenFWithFun (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: 'a -> float32 -> unit) =
731 areaOperationF img areas (Some f) AreaOperation.Opening
733 let areaCloseFWithFun (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f: 'a -> float32 -> unit) =
734 areaOperationF img areas (Some f) AreaOperation.Closing
736 // A simpler algorithm than 'areaOpen' but slower.
737 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
740 let imgData = img.Data
741 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
743 let histogram = Array.zeroCreate 256
744 for i in 0 .. h - 1 do
745 for j in 0 .. w - 1 do
746 let v = imgData.[i, j, 0] |> int
747 histogram.[v] <- histogram.[v] + 1
749 let flooded : bool[,] = Array2D.zeroCreate h w
751 let pointsChecked = HashSet<Point>()
752 let pointsToCheck = Stack<Point>()
754 for level in 255 .. -1 .. 0 do
755 let mutable n = histogram.[level]
758 for i in 0 .. h - 1 do
759 for j in 0 .. w - 1 do
760 if not flooded.[i, j] && imgData.[i, j, 0] = byte level
762 let mutable maxNeighborValue = 0uy
763 pointsChecked.Clear()
764 pointsToCheck.Clear()
765 pointsToCheck.Push(Point(j, i))
767 while pointsToCheck.Count > 0 do
768 let next = pointsToCheck.Pop()
769 pointsChecked.Add(next) |> ignore
770 flooded.[next.Y, next.X] <- true
773 let p = Point(next.X + nx, next.Y + ny)
774 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
776 let v = imgData.[p.Y, p.X, 0]
779 if not (pointsChecked.Contains(p))
781 pointsToCheck.Push(p)
782 elif v > maxNeighborValue
784 maxNeighborValue <- v
786 if int maxNeighborValue < level && pointsChecked.Count <= area
788 for p in pointsChecked do
789 imgData.[p.Y, p.X, 0] <- maxNeighborValue
791 // Zhang and Suen algorithm.
792 // Modify 'mat
' in place.
793 let thin (mat: Matrix<byte>) =
796 let mutable data1 = mat.Data
797 let mutable data2 = Array2D.copy data1
799 let mutable pixelChanged = true
800 let mutable oddIteration = true
802 while pixelChanged do
803 pixelChanged <- false
806 if data1.[i, j] = 1uy
808 let p2 = if i = 0 then 0uy else data1.[i-1, j]
809 let p3 = if i = 0 || j = w-1 then 0uy else data1.[i-1, j+1]
810 let p4 = if j = w-1 then 0uy else data1.[i, j+1]
811 let p5 = if i = h-1 || j = w-1 then 0uy else data1.[i+1, j+1]
812 let p6 = if i = h-1 then 0uy else data1.[i+1, j]
813 let p7 = if i = h-1 || j = 0 then 0uy else data1.[i+1, j-1]
814 let p8 = if j = 0 then 0uy else data1.[i, j-1]
815 let p9 = if i = 0 || j = 0 then 0uy else data1.[i-1, j-1]
817 let sumNeighbors = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
818 if sumNeighbors >= 2uy && sumNeighbors <= 6uy &&
819 (if p2 = 0uy && p3 = 1uy then 1 else 0) +
820 (if p3 = 0uy && p4 = 1uy then 1 else 0) +
821 (if p4 = 0uy && p5 = 1uy then 1 else 0) +
822 (if p5 = 0uy && p6 = 1uy then 1 else 0) +
823 (if p6 = 0uy && p7 = 1uy then 1 else 0) +
824 (if p7 = 0uy && p8 = 1uy then 1 else 0) +
825 (if p8 = 0uy && p9 = 1uy then 1 else 0) +
826 (if p9 = 0uy && p2 = 1uy then 1 else 0) = 1 &&
828 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
829 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
836 oddIteration <- not oddIteration
841 // Remove all 8-connected pixels with an area equal or greater than 'areaSize
'.
842 // Modify 'mat
' in place.
843 let removeArea (mat: Matrix<byte>) (areaSize: int) =
854 use mat' = new Matrix<byte
>(mat.Size)
860 let data' = mat'.Data
864 if data'.[i
, j] = 1uy
866 let neighborhood = List<Point>()
867 let neighborsToCheck = Stack<Point>()
868 neighborsToCheck.Push(Point(j, i
))
871 while neighborsToCheck.Count > 0 do
872 let n = neighborsToCheck.Pop()
874 for (ni, nj) in neighbors do
877 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
879 neighborsToCheck.Push(Point(pj, pi))
880 data'.[pi, pj] <- 0uy
881 if neighborhood.Count <= areaSize
883 for n in neighborhood do
884 data.[n.Y, n.X] <- 0uy
886 let connectedComponents (img: Image<Gray, byte>) (startPoints: List<Point>) : List<Point> =
890 let pointChecked = Points()
891 let pointToCheck = Stack<Point>(startPoints);
895 while pointToCheck.Count > 0 do
896 let next = pointToCheck.Pop()
897 pointChecked.Add(next) |> ignore
900 if ny <> 0 && nx <> 0
902 let p = Point(next.X + nx, next.Y + ny)
903 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)
907 List<Point>(pointChecked)
909 let drawLine (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0
: int) (y0
: int) (x1
: int) (y1
: int) (thickness
: int) =
910 img.Draw(LineSegment2D(Point(x0
, y0
), Point(x1
, y1
)), color
, thickness
);
912 let drawLineF (img: Image<'TColor, 'TDepth>) (color
: 'TColor) (x0: float) (y0: float) (x1: float) (y1: float) (thickness: int) =
913 img.Draw(LineSegment2DF(PointF(float32 x0, float32 y0), PointF(float32 x1, float32 y1)), color, thickness, CvEnum.LineType.AntiAlias);
915 let drawEllipse (img: Image<'TColor, 'TDepth>) (e: Types.Ellipse) (color: 'TColor) (alpha
: float) =
918 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)
920 let windowPosX = e
.Cx - e
.A - 5.f
921 let gapX = windowPosX - (float32
(int windowPosX))
923 let windowPosY = e
.Cy - e
.A - 5.f
924 let gapY = windowPosY - (float32
(int windowPosY))
926 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e
.A + 5.f) |> int, 2.f * (e
.A + 5.f) |> int)
929 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
931 use i = new Image<'TColor, 'TDepth>(img.ROI.Size)
932 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)
933 CvInvoke.AddWeighted(img, 1.0, i, alpha
, 0.0, img)
934 img.ROI <- Rectangle.Empty
936 let drawEllipses (img: Image<'TColor, 'TDepth>) (ellipses
: Types.Ellipse list) (color
: 'TColor) (alpha: float) =
937 List.iter (fun e -> drawEllipse img e color alpha) ellipses
939 let rngCell = System.Random()
940 let drawCell (img: Image<Bgr, byte>) (drawCellContent: bool) (c: Types.Cell) =
943 let colorB = rngCell.Next(20, 70)
944 let colorG = rngCell.Next(20, 70)
945 let colorR = rngCell.Next(20, 70)
947 for y in 0 .. c.elements.Height - 1 do
948 for x in 0 .. c.elements.Width - 1 do
949 if c.elements.[y, x] > 0uy
951 let dx, dy = c.center.X - c.elements.Width / 2, c.center.Y - c.elements.Height / 2
952 let b = img.Data.[y + dy, x + dx, 0] |> int
953 let g = img.Data.[y + dy, x + dx, 1] |> int
954 let r = img.Data.[y + dy, x + dx, 2] |> int
955 img.Data.[y + dy, x + dx, 0] <- if b + colorB > 255 then 255uy else byte (b + colorB)
956 img.Data.[y + dy, x + dx, 1] <- if g + colorG > 255 then 255uy else byte (g + colorG)
957 img.Data.[y + dy, x + dx, 2] <- if r + colorR > 255 then 255uy else byte (r + colorR)
959 let crossColor, crossColor2 =
960 match c.cellClass with
961 | Types.HealthyRBC -> Bgr(255., 0., 0.), Bgr(255., 255., 255.)
962 | Types.InfectedRBC -> Bgr(0., 0., 255.), Bgr(120., 120., 255.)
963 | Types.Peculiar -> Bgr(0., 0., 0.), Bgr(80., 80., 80.)
965 drawLine img crossColor2 (c.center.X - 3) c.center.Y (c.center.X + 3) c.center.Y 2
966 drawLine img crossColor2 c.center.X (c.center.Y - 3) c.center.X (c.center.Y + 3) 2
968 drawLine img crossColor (c.center.X - 3) c.center.Y (c.center.X + 3) c.center.Y 1
969 drawLine img crossColor c.center.X (c.center.Y - 3) c.center.X (c.center.Y + 3) 1
972 let drawCells (img: Image<Bgr, byte>) (drawCellContent: bool) (cells: Types.Cell list) =
973 List.iter (fun c -> drawCell img drawCellContent c) cells