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)
35 type Histogram = { data: int[]; total: int; sum: int; min: float32; max: float32 }
37 let histogramImg (img: Image<Gray, float32>) (nbSamples: int) : Histogram =
38 let imgData = img.Data
41 let min = ref [| 0.0 |]
42 let minLocation = ref <| [| Point() |]
43 let max = ref [| 0.0 |]
44 let maxLocation = ref <| [| Point() |]
45 img.MinMax(min, max, minLocation, maxLocation)
46 float32 (!min).[0], float32 (!max).[0]
48 let bin (x: float32) : int =
49 let p = int ((x - min) / (max - min) * float32 nbSamples)
50 if p >= nbSamples then nbSamples - 1 else p
52 let data = Array.zeroCreate nbSamples
54 for i in 0 .. img.Height - 1 do
55 for j in 0 .. img.Width - 1 do
56 let p = bin imgData.[i, j, 0]
57 data.[p] <- data.[p] + 1
59 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
61 let histogramMat (mat: Matrix<float32>) (nbSamples: int) : Histogram =
62 let matData = mat.Data
66 let minLocation = ref <| Point()
68 let maxLocation = ref <| Point()
69 mat.MinMax(min, max, minLocation, maxLocation)
70 float32 !min, float32 !max
72 let bin (x: float32) : int =
73 let p = int ((x - min) / (max - min) * float32 nbSamples)
74 if p >= nbSamples then nbSamples - 1 else p
76 let data = Array.zeroCreate nbSamples
78 for i in 0 .. mat.Height - 1 do
79 for j in 0 .. mat.Width - 1 do
80 let p = bin matData.[i, j]
81 data.[p] <- data.[p] + 1
83 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
85 let histogram (values: float32 seq) (nbSamples: int) : Histogram =
86 let mutable min = Single.MaxValue
87 let mutable max = Single.MinValue
92 if v < min then min <- v
93 if v > max then max <- v
95 let bin (x: float32) : int =
96 let p = int ((x - min) / (max - min) * float32 nbSamples)
97 if p >= nbSamples then nbSamples - 1 else p
99 let data = Array.zeroCreate nbSamples
103 data.[p] <- data.[p] + 1
105 { data = data; total = n; sum = Array.sum data; min = min; max = max }
107 let otsu (hist: Histogram) : float32 * float32 * float32 =
110 let mutable maximum = 0.0
111 let mutable level = 0
112 let sum = hist.data |> Array.mapi (fun i v -> i * v) |> Array.sum |> float
114 for i in 0 .. hist.data.Length - 1 do
115 wB <- wB + hist.data.[i]
118 let wF = hist.total - wB
121 sumB <- sumB + i * hist.data.[i]
122 let mB = (float sumB) / (float wB)
123 let mF = (sum - float sumB) / (float wF)
124 let between = (float wB) * (float wF) * (mB - mF) ** 2.;
125 if between >= maximum
133 for i in 0 .. level - 1 do
134 sum <- sum + i * hist.data.[i]
135 nb <- nb + hist.data.[i]
136 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
141 for i in level + 1 .. hist.data.Length - 1 do
142 sum <- sum + i * hist.data.[i]
143 nb <- nb + hist.data.[i]
144 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
147 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
149 toFloat level, toFloat mean1, toFloat mean2
152 let suppressMConnections (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 let findEdges (img: Image<Gray, float32>) : Matrix<byte> * Image<Gray, float32> * Image<Gray, float32> =
172 new ConvolutionKernelF(array2D [[ 1.0f; 0.0f; -1.0f ]
173 [ 2.0f; 0.0f; -2.0f ]
174 [ 1.0f; 0.0f; -1.0f ]], Point(1, 1))
176 let xGradient = img.Convolution(sobelKernel)
177 let yGradient = img.Convolution(sobelKernel.Transpose())
179 let xGradientData = xGradient.Data
180 let yGradientData = yGradient.Data
181 for r in 0 .. h - 1 do
182 xGradientData.[r, 0, 0] <- 0.f
183 xGradientData.[r, w - 1, 0] <- 0.f
184 yGradientData.[r, 0, 0] <- 0.f
185 yGradientData.[r, w - 1, 0] <- 0.f
187 for c in 0 .. w - 1 do
188 xGradientData.[0, c, 0] <- 0.f
189 xGradientData.[h - 1, c, 0] <- 0.f
190 yGradientData.[0, c, 0] <- 0.f
191 yGradientData.[h - 1, c, 0] <- 0.f
193 use magnitudes = new Matrix<float32>(xGradient.Size)
194 use angles = new Matrix<float32>(xGradient.Size)
195 CvInvoke.CartToPolar(xGradient, yGradient, magnitudes, angles) // Compute the magnitudes (without angles).
197 let thresholdHigh, thresholdLow =
198 let sensibilityHigh = 0.1f
199 let sensibilityLow = 0.0f
200 use magnitudesByte = magnitudes.Convert<byte>()
201 let threshold = float32 <| CvInvoke.Threshold(magnitudesByte, magnitudesByte, 0.0, 1.0, CvEnum.ThresholdType.Otsu ||| CvEnum.ThresholdType.Binary)
202 let threshold, _, _ = otsu (histogramMat magnitudes 300)
204 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
206 // Non-maximum suppression.
207 use nms = new Matrix<byte>(xGradient.Size)
209 let nmsData = nms.Data
210 let anglesData = angles.Data
211 let magnitudesData = magnitudes.Data
212 let xGradientData = xGradient.Data
213 let yGradientData = yGradient.Data
215 let PI = float32 Math.PI
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
289 let gaussianFilter (img : Image<'TColor, 'TDepth>) (standardDeviation
: float) : Image<'TColor, 'TDepth> =
290 let size = 2 * int (ceil
(4.0 * standardDeviation
)) + 1
291 img.SmoothGaussian(size, size, standardDeviation
, standardDeviation
)
294 type Points = HashSet<Point>
296 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
298 img.Data.[p.Y, p.X, 0] <- intensity
304 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
307 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
309 let imgData = img.Data
310 let suppress: bool[,] = Array2D.zeroCreate h w
312 let result = List<List<Point>>()
314 let flood (start: Point) : List<List<Point>> =
315 let sameLevelToCheck = Stack<Point>()
316 let betterLevelToCheck = Stack<Point>()
317 betterLevelToCheck.Push(start)
319 let result' = List<List<Point>>()
321 while betterLevelToCheck.Count > 0 do
322 let p = betterLevelToCheck.Pop()
323 if not suppress.[p.Y, p.X]
325 suppress.[p.Y, p.X] <- true
326 sameLevelToCheck.Push(p)
327 let current = List<Point>()
329 let mutable betterExists = false
331 while sameLevelToCheck.Count > 0 do
332 let p' = sameLevelToCheck.Pop()
333 let currentLevel = imgData.[p'.Y, p'.X, 0]
334 current.Add(p') |> ignore
338 if ni >= 0 && ni < h && nj >= 0 && nj < w
340 let level = imgData.[ni, nj, 0]
341 let notSuppressed = not suppress.[ni, nj]
343 if level = currentLevel && notSuppressed
345 suppress.[ni, nj] <- true
346 sameLevelToCheck.Push(Point(nj, ni))
347 elif
if extremumType
= ExtremumType.Maxima then level > currentLevel else level < currentLevel
352 betterLevelToCheck.Push(Point(nj, ni))
359 for i
in 0 .. h - 1 do
360 for j in 0 .. w - 1 do
361 let maxima = flood (Point(j, i
))
364 result.AddRange(maxima)
366 result.Select(fun l
-> Points(l
))
369 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
370 findExtremum img ExtremumType.Maxima
373 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
374 findExtremum img ExtremumType.Minima
377 type PriorityQueue () =
379 let q: Points[] = Array.init
size (fun i
-> Points())
380 let mutable highest = -1 // Value of the first elements of 'q'.
381 let mutable lowest = size
383 member this
.NextMax () : byte
* Point =
386 invalidOp
"Queue is empty"
390 l.Remove(next) |> ignore
391 let value = byte
highest
395 highest <- highest - 1
396 while highest > lowest && q.[highest].Count = 0 do
397 highest <- highest - 1
405 member this
.NextMin () : byte
* Point =
408 invalidOp
"Queue is empty"
410 let l = q.[lowest + 1]
412 l.Remove(next) |> ignore
413 let value = byte
(lowest + 1)
418 while lowest < highest && q.[lowest + 1].Count = 0 do
433 member this
.Add (value: byte
) (p: Point) =
443 q.[vi].Add(p) |> ignore
445 member this
.Remove (value: byte
) (p: Point) =
447 if q.[vi].Remove(p) && q.[vi].Count = 0
451 highest <- highest - 1
452 while highest > lowest && q.[highest].Count = 0 do
453 highest <- highest - 1
457 while lowest < highest && q.[lowest + 1].Count = 0 do
460 if highest = lowest // The queue is now empty.
465 member this
.IsEmpty =
468 member this
.Clear () =
469 while highest > lowest do
471 highest <- highest - 1
476 type private AreaState =
481 type private AreaOperation =
486 type private Area (elements
: Points) =
487 member this
.Elements = elements
488 member val Intensity = None with get
, set
489 member val State = AreaState.Unprocessed with get
, set
491 let private areaOperation
(img: Image<Gray, byte
>) (area
: int) (op
: AreaOperation) =
494 let imgData = img.Data
495 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
497 let areas = List<Area>((if op
= AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map
Area)
499 let pixels: Area[,] = Array2D.create
h w null
501 for e
in m.Elements do
502 pixels.[e
.Y, e
.X] <- m
504 let queue = PriorityQueue()
506 let addEdgeToQueue (elements
: Points) =
511 let p' = Point(nj, ni)
512 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
514 queue.Add (imgData.[ni, nj, 0]) p'
516 // Reverse order is quicker.
517 for i in areas.Count - 1 .. -1 .. 0 do
519 if m.Elements.Count <= area && m.State <> AreaState.Removed
522 addEdgeToQueue m.Elements
524 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
525 let nextElements = Points()
527 let mutable stop = false
529 let intensity', p = if op
= AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
530 let mutable merged = false
532 if intensity' = intensity // The intensity doesn't
change.
534 if m.Elements.Count + nextElements.Count + 1 > area
536 m.State <- AreaState.Validated
537 m.Intensity <- Some intensity
540 nextElements.Add(p) |> ignore
542 elif
if op
= AreaOperation.Opening then intensity' < intensity else intensity' > intensity
544 m.Elements.UnionWith(nextElements)
545 for e
in nextElements do
546 pixels.[e
.Y, e
.X] <- m
548 if m.Elements.Count = area
550 m.State <- AreaState.Validated
551 m.Intensity <- Some (intensity')
554 intensity <- intensity'
556 nextElements.Add(p) |> ignore
559 let m' = pixels.[p.Y, p.X]
562 if m'.Elements.Count + m.Elements.Count <= area
564 m'.State <- AreaState.Removed
565 for e
in m'.Elements do
566 pixels.[e.Y, e.X] <- m
567 queue.Remove imgData.[e.Y, e.X, 0] e
568 addEdgeToQueue m'.Elements
569 m.Elements.UnionWith(m'.Elements)
570 let intensityMax = if op = AreaOperation.Opening then queue.Max else queue.Min
571 if intensityMax <> intensity
573 intensity <- intensityMax
579 m.State <- AreaState.Validated
580 m.Intensity <- Some (intensity)
583 if not stop && not merged
588 let p' = Point(nj, ni)
589 if ni < 0 || ni >= h || nj < 0 || nj >= w
591 m.State <- AreaState.Validated
592 m.Intensity <- Some (intensity)
594 elif
not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
596 queue.Add (imgData.[ni, nj, 0]) p'
600 if m.Elements.Count + nextElements.Count <= area
602 m.State <- AreaState.Validated
603 m.Intensity <- Some intensity'
604 m.Elements.UnionWith(nextElements)
608 if m.State = AreaState.Validated
610 match m.Intensity with
612 for p in m.Elements do
613 imgData.[p.Y, p.X, 0] <- i
618 let areaOpen (img: Image<Gray, byte
>) (area
: int) =
619 areaOperation
img area
AreaOperation.Opening
621 let areaClose (img: Image<Gray, byte
>) (area
: int) =
622 areaOperation
img area
AreaOperation.Closing
625 type Island (cmp
: IComparer<float32
>) =
626 member val Shore = Heap.Heap<float32
, Point>(cmp
) with get
627 member val Level = 0.f
with get
, set
628 member val Surface = 0 with get
, set
631 let private areaOperationF
(img: Image<Gray, float32
>) (area
: int) (op
: AreaOperation) =
635 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
637 let comparer = if op
= AreaOperation.Opening
638 then { new IComparer<float32
> with member this
.Compare(v1
, v2
) = v1
.CompareTo(v2
) }
639 else { new IComparer<float32
> with member this
.Compare(v1
, v2
) = v2
.CompareTo(v1
) }
641 let ownership: Island[,] = Array2D.create
h w null
643 // Initialize islands with their shore.
644 let islands = List<Island>()
645 let extremum = img |> if op
= AreaOperation.Opening then findMaxima else findMinima
649 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e
.Count)
651 let shorePoints = Points()
653 ownership.[p.Y, p.X] <- island
657 let neighbor = Point(nj, ni)
658 if ni >= 0 && ni < h && nj >= 0 && nj < w && ownership.[ni, nj] = null && not (shorePoints.Contains(neighbor))
660 shorePoints.Add(neighbor) |> ignore
661 island.Shore.Add earth.[ni, nj, 0] neighbor
663 for island in islands do
664 let mutable stop = island.Shore.IsEmpty
666 // 'true' if 'p' is owned or adjacent to 'island'.
667 let ownedOrAdjacent (p: Point) : bool =
668 ownership.[p.Y, p.X] = island ||
669 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
670 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
671 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
672 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
674 while not stop && island.Surface < area
do
675 let level, next = island.Shore.Max
676 let other = ownership.[next.Y, next.X]
677 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
679 island.Shore.RemoveNext ()
682 then // We touching another island.
683 if island.Surface + other.Surface >= area
686 else // We can merge 'other' into 'surface'.
687 island.Surface <- island.Surface + other.Surface
688 island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then island.Level else other.Level
689 for l, p in other.Shore do
690 let mutable currentY = p.Y + 1
691 while currentY < h && ownership.[currentY, p.X] = other do
692 ownership.[currentY, p.X] <- island
693 currentY <- currentY + 1
697 elif
comparer.Compare(level, island.Level) > 0
701 island.Shore.RemoveNext ()
705 if ni < 0 || ni >= h || nj < 0 || nj >= w
707 island.Surface <- Int32.MaxValue
710 let neighbor = Point(nj, ni)
711 if not <| ownedOrAdjacent neighbor
713 island.Shore.Add earth.[ni, nj, 0] neighbor
716 ownership.[next.Y, next.X] <- island
717 island.Level <- level
718 island.Surface <- island.Surface + 1
720 for i
in 0 .. h - 1 do
721 for j in 0 .. w - 1 do
722 let island = ownership.[i
, j]
725 earth.[i
, j, 0] <- island.Level
729 let areaOpenF (img: Image<Gray, float32
>) (area
: int) =
730 areaOperationF
img area
AreaOperation.Opening
732 let areaCloseF (img: Image<Gray, float32
>) (area
: int) =
733 areaOperationF
img area
AreaOperation.Closing
735 // A simpler algorithm than 'areaOpen' but slower.
736 let areaOpen2 (img: Image<Gray, byte
>) (area
: int) =
739 let imgData = img.Data
740 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
742 let histogram = Array.zeroCreate
256
743 for i
in 0 .. h - 1 do
744 for j in 0 .. w - 1 do
745 let v = imgData.[i
, j, 0] |> int
746 histogram.[v] <- histogram.[v] + 1
748 let flooded : bool[,] = Array2D.zeroCreate
h w
750 let pointsChecked = HashSet<Point>()
751 let pointsToCheck = Stack<Point>()
753 for level in 255 .. -1 .. 0 do
754 let mutable n = histogram.[level]
757 for i
in 0 .. h - 1 do
758 for j in 0 .. w - 1 do
759 if not flooded.[i
, j] && imgData.[i
, j, 0] = byte
level
761 let mutable maxNeighborValue = 0uy
762 pointsChecked.Clear()
763 pointsToCheck.Clear()
764 pointsToCheck.Push(Point(j, i
))
766 while pointsToCheck.Count > 0 do
767 let next = pointsToCheck.Pop()
768 pointsChecked.Add(next) |> ignore
769 flooded.[next.Y, next.X] <- true
772 let p = Point(next.X + nx
, next.Y + ny
)
773 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
775 let v = imgData.[p.Y, p.X, 0]
778 if not (pointsChecked.Contains(p))
780 pointsToCheck.Push(p)
781 elif
v > maxNeighborValue
783 maxNeighborValue <- v
785 if int maxNeighborValue < level && pointsChecked.Count <= area
787 for p in pointsChecked do
788 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
842 // Remove all 8-connected pixels with an area equal or greater than 'areaSize'.
843 // Modify 'mat' in place.
844 let removeArea (mat
: Matrix<byte
>) (areaSize
: int) =
855 use mat' = new Matrix<byte>(mat.Size)
861 let data' = mat'.Data
865 if data'.[i, j] = 1uy
867 let neighborhood = List<Point>()
868 let neighborsToCheck = Stack<Point>()
869 neighborsToCheck.Push(Point(j, i))
872 while neighborsToCheck.Count > 0 do
873 let n = neighborsToCheck.Pop()
875 for (ni, nj) in neighbors do
878 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
880 neighborsToCheck.Push(Point(pj, pi))
881 data'.[pi, pj] <- 0uy
882 if neighborhood.Count <= areaSize
884 for n in neighborhood do
885 data.[n.Y, n.X] <- 0uy
887 let connectedComponents (img: Image<Gray, byte
>) (startPoints
: List<Point>) : List<Point> =
891 let pointChecked = Points()
892 let pointToCheck = Stack<Point>(startPoints
);
896 while pointToCheck.Count > 0 do
897 let next = pointToCheck.Pop()
898 pointChecked.Add(next) |> ignore
901 if ny
<> 0 && nx
<> 0
903 let p = Point(next.X + nx
, next.Y + ny
)
904 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)
908 List<Point>(pointChecked)
911 let drawLine (img: Image<'TColor, 'TDepth>) (color
: 'TColor) (x0: int) (y0: int) (x1: int) (y1: int) (thickness: int) =
912 img.Draw(LineSegment2D(Point(x0, y0), Point(x1, y1)), color, thickness);
915 let drawLineF (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0
: float) (y0
: float) (x1
: float) (y1
: float) (thickness
: int) =
916 img.Draw(LineSegment2DF(PointF(float32 x0
, float32 y0
), PointF(float32 x1
, float32 y1
)), color
, thickness
, CvEnum.LineType.AntiAlias);
919 let drawEllipse (img: Image<'TColor, 'TDepth>) (e
: Types.Ellipse) (color
: 'TColor) (alpha: float) =
923 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)
925 let windowPosX = e.Cx - e.A - 5.f
926 let gapX = windowPosX - (float32 (int windowPosX))
928 let windowPosY = e.Cy - e.A - 5.f
929 let gapY = windowPosY - (float32 (int windowPosY))
931 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e.A + 5.f) |> int, 2.f * (e.A + 5.f) |> int)
934 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
936 use i = new Image<'TColor, 'TDepth>(img.ROI.Size)
937 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)
938 CvInvoke.AddWeighted(img, 1.0, i, alpha, 0.0, img)
939 img.ROI <- Rectangle.Empty
942 let drawEllipses (img: Image<'TColor, 'TDepth>) (ellipses: Types.Ellipse list) (color: 'TColor) (alpha
: float) =
943 List.iter
(fun e
-> drawEllipse img e
color alpha
) ellipses
946 let rngCell = System.Random()
947 let drawCell (img: Image<Bgr, byte
>) (drawCellContent
: bool) (c
: Types.Cell) =
950 let colorB = rngCell.Next(20, 70)
951 let colorG = rngCell.Next(20, 70)
952 let colorR = rngCell.Next(20, 70)
954 for y
in 0 .. c
.elements
.Height - 1 do
955 for x
in 0 .. c
.elements
.Width - 1 do
956 if c
.elements
.[y
, x
] > 0uy
958 let dx, dy
= c
.center
.X - c
.elements
.Width / 2, c
.center
.Y - c
.elements
.Height / 2
959 let b = img.Data.[y
+ dy
, x
+ dx, 0] |> int
960 let g = img.Data.[y
+ dy
, x
+ dx, 1] |> int
961 let r = img.Data.[y
+ dy
, x
+ dx, 2] |> int
962 img.Data.[y
+ dy
, x
+ dx, 0] <- if b + colorB > 255 then 255uy else byte (b + colorB)
963 img.Data.[y
+ dy
, x
+ dx, 1] <- if g + colorG > 255 then 255uy else byte (g + colorG)
964 img.Data.[y
+ dy
, x
+ dx, 2] <- if r + colorR > 255 then 255uy else byte (r + colorR)
966 let crossColor, crossColor2
=
967 match c
.cellClass
with
968 | Types.HealthyRBC -> Bgr(255., 0., 0.), Bgr(255., 255., 255.)
969 | Types.InfectedRBC -> Bgr(0., 0., 255.), Bgr(120., 120., 255.)
970 | Types.Peculiar -> Bgr(0., 0., 0.), Bgr(80., 80., 80.)
972 drawLine img crossColor2
(c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 2
973 drawLine img crossColor2 c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 2
975 drawLine img crossColor (c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 1
976 drawLine img crossColor c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 1
979 let drawCells (img: Image<Bgr, byte>) (drawCellContent
: bool) (cells
: Types.Cell list) =
980 List.iter
(fun c
-> drawCell img drawCellContent
c) cells