cbb65b4d5368168dc7c55ab1167b683b19340e6e
1
module ParasitemiaCore.ImgTools
5 open System.Collections.Generic
16 let normalize (img
: Image<Gray, float32
>) (upperLimit
: float) : Image<Gray, float32
> =
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 let normalized = (img
- (!min).[0]) / ((!max).[0] - (!min).[0])
25 else upperLimit * normalized
27 let mergeChannels (img
: Image<Bgr, float32
>) (rgbWeights
: float * float * float) : Image<Gray, float32
> =
29 | 1., 0., 0. -> img
.[2]
30 | 0., 1., 0. -> img
.[1]
31 | 0., 0., 1. -> img
.[0]
32 | redFactor, greenFactor
, blueFactor
->
33 let result = new Image<Gray, float32
>(img
.Size)
34 CvInvoke.AddWeighted(result, 1., img
.[2], redFactor, 0., result)
35 CvInvoke.AddWeighted(result, 1., img
.[1], greenFactor
, 0., result)
36 CvInvoke.AddWeighted(result, 1., img
.[0], blueFactor
, 0., result)
39 let mergeChannelsWithProjection (img
: Image<Bgr, float32
>) (v1r
: float32
, v1g
: float32
, v1b
: float32
) (v2r
: float32
, v2g
: float32
, v2b
: float32
) (upperLimit: float) : Image<Gray, float32
> =
40 let vr, vg
, vb
= v2r
- v1r
, v2g
- v1g
, v2b
- v1b
41 let vMagnitude = sqrt
(vr ** 2.f
+ vg
** 2.f
+ vb
** 2.f
)
42 let project (r
: float32
) (g
: float32
) (b
: float32
) = ((r
- v1r
) * vr + (g
- v1g
) * vg
+ (b
- v1b
) * vb
) / vMagnitude
43 let result = new Image<Gray, float32
>(img
.Size)
44 // TODO: Essayer en bindant Data pour gagner du temps
45 for i
in 0 .. img
.Height - 1 do
46 for j
in 0 .. img
.Width - 1 do
47 result.Data.[i
, j
, 0] <- project img.Data.[i
, j
, 2] img.Data.[i
, j
, 1] img.Data.[i
, j
, 0]
48 normalize result upperLimit
50 // Normalize image values between 0uy and 255uy.
51 let normalizeAndConvert (img: Image<Gray, 'TDepth>) : Image<Gray, byte> =
52 (normalize (img.Convert<Gray, float32>()) 255.).Convert<Gray, byte>()
54 let saveImg (img: Image<'TColor, 'TDepth>) (filepath: string) =
57 let saveMat (mat: Matrix<'TDepth>) (filepath
: string) =
58 use img = new Image<Gray, 'TDeph>(mat.Size)
62 type Histogram = { data: int[]; total: int; sum: int; min: float32; max: float32 }
64 let histogramImg (img: Image<Gray, float32>) (nbSamples: int) : Histogram =
65 let imgData = img.Data
68 let min = ref [| 0.0 |]
69 let minLocation = ref <| [| Point() |]
70 let max = ref [| 0.0 |]
71 let maxLocation = ref <| [| Point() |]
72 img.MinMax(min, max, minLocation, maxLocation)
73 float32 (!min).[0], float32 (!max).[0]
75 let inline bin (x: float32) : int =
76 let p = int ((x - min) / (max - min) * float32 nbSamples)
77 if p >= nbSamples then nbSamples - 1 else p
79 let data = Array.zeroCreate nbSamples
81 for i in 0 .. img.Height - 1 do
82 for j in 0 .. img.Width - 1 do
83 let p = bin imgData.[i, j, 0]
84 data.[p] <- data.[p] + 1
86 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
88 let histogramMat (mat: Matrix<float32>) (nbSamples: int) : Histogram =
89 let matData = mat.Data
93 let minLocation = ref <| Point()
95 let maxLocation = ref <| Point()
96 mat.MinMax(min, max, minLocation, maxLocation)
97 float32 !min, float32 !max
99 let inline bin (x: float32) : int =
100 let p = int ((x - min) / (max - min) * float32 nbSamples)
101 if p >= nbSamples then nbSamples - 1 else p
103 let data = Array.zeroCreate nbSamples
105 for i in 0 .. mat.Height - 1 do
106 for j in 0 .. mat.Width - 1 do
107 let p = bin matData.[i, j]
108 data.[p] <- data.[p] + 1
110 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
112 let histogram (values: float32 seq) (nbSamples: int) : Histogram =
113 let mutable min = Single.MaxValue
114 let mutable max = Single.MinValue
119 if v < min then min <- v
120 if v > max then max <- v
122 let inline bin (x: float32) : int =
123 let p = int ((x - min) / (max - min) * float32 nbSamples)
124 if p >= nbSamples then nbSamples - 1 else p
126 let data = Array.zeroCreate nbSamples
130 data.[p] <- data.[p] + 1
132 { data = data; total = n; sum = Array.sum data; min = min; max = max }
134 let otsu (hist: Histogram) : float32 * float32 * float32 =
137 let mutable maximum = 0.0
138 let mutable level = 0
139 let sum = hist.data |> Array.mapi (fun i v -> i * v |> float) |> Array.sum
141 for i in 0 .. hist.data.Length - 1 do
142 wB <- wB + hist.data.[i]
145 let wF = hist.total - wB
148 sumB <- sumB + i * hist.data.[i]
149 let mB = (float sumB) / (float wB)
150 let mF = (sum - float sumB) / (float wF)
151 let between = (float wB) * (float wF) * (mB - mF) ** 2.;
152 if between >= maximum
160 for i in 0 .. level - 1 do
161 sum <- sum + i * hist.data.[i]
162 nb <- nb + hist.data.[i]
163 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
168 for i in level + 1 .. hist.data.Length - 1 do
169 sum <- sum + i * hist.data.[i]
170 nb <- nb + hist.data.[i]
171 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
174 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
176 toFloat level, toFloat mean1, toFloat mean2
179 /// Remove M-adjacent pixels. It may be used after thinning.
181 let suppressMAdjacency (img: Matrix<byte>) =
184 for i in 1 .. h - 2 do
185 for j in 1 .. w - 2 do
186 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)
189 for i in 1 .. h - 2 do
190 for j in 1 .. w - 2 do
191 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)
196 /// Find edges of an image by using the Canny approach.
197 /// The thresholds are automatically defined with otsu on gradient magnitudes.
199 /// <param name="img"></param>
200 let findEdges (img: Image<Gray, float32>) : Matrix<byte> * Matrix<float32> * Matrix<float32> =
205 new Matrix<float32>(array2D [[ 1.0f; 0.0f; -1.0f ]
206 [ 2.0f; 0.0f; -2.0f ]
207 [ 1.0f; 0.0f; -1.0f ]])
209 let xGradient = new Matrix<float32>(img.Size)
210 let yGradient = new Matrix<float32>(img.Size)
211 CvInvoke.Filter2D(img, xGradient, sobelKernel, Point(1, 1))
212 CvInvoke.Filter2D(img, yGradient, sobelKernel.Transpose(), Point(1, 1))
214 use magnitudes = new Matrix<float32>(xGradient.Size)
215 use angles = new Matrix<float32>(xGradient.Size)
216 CvInvoke.CartToPolar(xGradient, yGradient, magnitudes, angles) // Compute the magnitudes and angles.
218 let thresholdHigh, thresholdLow =
219 let sensibilityHigh = 0.1f
220 let sensibilityLow = 0.0f
221 let threshold, _, _ = otsu (histogramMat magnitudes 300)
222 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
224 // Non-maximum suppression.
225 use nms = new Matrix<byte>(xGradient.Size)
227 let nmsData = nms.Data
228 let anglesData = angles.Data
229 let magnitudesData = magnitudes.Data
230 let xGradientData = xGradient.Data
231 let yGradientData = yGradient.Data
233 for i in 0 .. h - 1 do
234 nmsData.[i, 0] <- 0uy
235 nmsData.[i, w - 1] <- 0uy
237 for j in 0 .. w - 1 do
238 nmsData.[0, j] <- 0uy
239 nmsData.[h - 1, j] <- 0uy
241 for i in 1 .. h - 2 do
242 for j in 1 .. w - 2 do
243 let vx = xGradientData.[i, j]
244 let vy = yGradientData.[i, j]
245 if vx <> 0.f || vy <> 0.f
247 let angle = anglesData.[i, j]
249 let vx', vy' = abs vx, abs vy
250 let ratio2 = if vx' > vy' then vy' / vx' else vx' / vy'
251 let ratio1 = 1.f - ratio2
253 let mNeigbors (sign: int) : float32 =
255 then ratio1 * magnitudesData.[i, j + sign] + ratio2 * magnitudesData.[i + sign, j + sign]
256 elif angle < PI / 2.f
257 then ratio2 * magnitudesData.[i + sign, j + sign] + ratio1 * magnitudesData.[i + sign, j]
258 elif angle < 3.f * PI / 4.f
259 then ratio1 * magnitudesData.[i + sign, j] + ratio2 * magnitudesData.[i + sign, j - sign]
261 then ratio2 * magnitudesData.[i + sign, j - sign] + ratio1 * magnitudesData.[i, j - sign]
262 elif angle < 5.f * PI / 4.f
263 then ratio1 * magnitudesData.[i, j - sign] + ratio2 * magnitudesData.[i - sign, j - sign]
264 elif angle < 3.f * PI / 2.f
265 then ratio2 * magnitudesData.[i - sign, j - sign] + ratio1 * magnitudesData.[i - sign, j]
266 elif angle < 7.f * PI / 4.f
267 then ratio1 * magnitudesData.[i - sign, j] + ratio2 * magnitudesData.[i - sign, j + sign]
268 else ratio2 * magnitudesData.[i - sign, j + sign] + ratio1 * magnitudesData.[i, j + sign]
270 let m = magnitudesData.[i, j]
271 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
273 nmsData.[i, j] <- 1uy
275 // suppressMConnections nms // It's
not helpful
for the rest of the process (ellipse
detection).
277 let edges = new Matrix<byte
>(xGradient.Size)
278 let edgesData = edges.Data
280 // Hysteresis thresholding.
281 let toVisit = Stack<Point>()
282 for i
in 0 .. h - 1 do
283 for j
in 0 .. w - 1 do
284 if nmsData.[i
, j
] = 1uy && magnitudesData.[i
, j
] >= thresholdHigh
286 nmsData.[i
, j
] <- 0uy
287 toVisit.Push(Point(j
, i
))
288 while toVisit.Count > 0 do
289 let p = toVisit.Pop()
290 edgesData.[p.Y, p.X] <- 1uy
293 if i
' <> 0 || j' <> 0
297 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
299 nmsData.[ni, nj] <- 0uy
300 toVisit.Push(Point(nj, ni))
302 edges, xGradient, yGradient
304 let gaussianFilter (img : Image<'TColor, 'TDepth>) (standardDeviation
: float) : Image<'TColor, 'TDepth> =
305 let size = 2 * int (ceil
(4.0 * standardDeviation
)) + 1
306 img.SmoothGaussian(size, size, standardDeviation
, standardDeviation
)
308 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
310 img.Data.[p.Y, p.X, 0] <- intensity
316 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
319 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
321 let imgData = img.Data
322 let suppress: bool[,] = Array2D.zeroCreate h w
324 let result = List<List<Point>>()
326 let flood (start: Point) : List<List<Point>> =
327 let sameLevelToCheck = Stack<Point>()
328 let betterLevelToCheck = Stack<Point>()
329 betterLevelToCheck.Push(start)
331 let result' = List<List<Point>>()
333 while betterLevelToCheck.Count > 0 do
334 let p = betterLevelToCheck.Pop()
335 if not suppress.[p.Y, p.X]
337 suppress.[p.Y, p.X] <- true
338 sameLevelToCheck.Push(p)
339 let current = List<Point>()
341 let mutable betterExists = false
343 while sameLevelToCheck.Count > 0 do
344 let p' = sameLevelToCheck.Pop()
345 let currentLevel = imgData.[p'.Y, p'.X, 0]
346 current.Add(p') |> ignore
350 if ni >= 0 && ni < h && nj >= 0 && nj < w
352 let level = imgData.[ni, nj, 0]
353 let notSuppressed = not suppress.[ni, nj]
355 if level = currentLevel && notSuppressed
357 suppress.[ni, nj] <- true
358 sameLevelToCheck.Push(Point(nj, ni))
359 elif
if extremumType
= ExtremumType.Maxima then level > currentLevel else level < currentLevel
364 betterLevelToCheck.Push(Point(nj, ni))
371 for i
in 0 .. h - 1 do
372 for j in 0 .. w - 1 do
373 let maxima = flood (Point(j, i
))
376 result.AddRange(maxima)
378 result.Select(fun l
-> Points(l
))
380 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
381 findExtremum img ExtremumType.Maxima
383 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
384 findExtremum img ExtremumType.Minima
386 type PriorityQueue () =
388 let q: Points[] = Array.init
size (fun i
-> Points())
389 let mutable highest = -1 // Value of the first elements of 'q'.
390 let mutable lowest = size
392 member this
.NextMax () : byte
* Point =
395 invalidOp
"Queue is empty"
399 l.Remove(next) |> ignore
400 let value = byte
highest
404 highest <- highest - 1
405 while highest > lowest && q.[highest].Count = 0 do
406 highest <- highest - 1
414 member this
.NextMin () : byte
* Point =
417 invalidOp
"Queue is empty"
419 let l = q.[lowest + 1]
421 l.Remove(next) |> ignore
422 let value = byte
(lowest + 1)
427 while lowest < highest && q.[lowest + 1].Count = 0 do
442 member this
.Add (value: byte
) (p: Point) =
452 q.[vi].Add(p) |> ignore
454 member this
.Remove (value: byte
) (p: Point) =
456 if q.[vi].Remove(p) && q.[vi].Count = 0
460 highest <- highest - 1
461 while highest > lowest && q.[highest].Count = 0 do
462 highest <- highest - 1
466 while lowest < highest && q.[lowest + 1].Count = 0 do
469 if highest = lowest // The queue is now empty.
474 member this
.IsEmpty =
477 member this
.Clear () =
478 while highest > lowest do
480 highest <- highest - 1
484 type private AreaState =
489 type private AreaOperation =
494 type private Area (elements
: Points) =
495 member this
.Elements = elements
496 member val Intensity = None with get
, set
497 member val State = AreaState.Unprocessed with get
, set
499 let private areaOperation
(img: Image<Gray, byte
>) (area
: int) (op
: AreaOperation) =
502 let imgData = img.Data
503 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
505 let areas = List<Area>((if op
= AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map
Area)
507 let pixels: Area[,] = Array2D.create
h w null
509 for e
in m.Elements do
510 pixels.[e
.Y, e
.X] <- m
512 let queue = PriorityQueue()
514 let addEdgeToQueue (elements
: Points) =
519 let p' = Point(nj, ni)
520 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
522 queue.Add (imgData.[ni, nj, 0]) p'
524 // Reverse order is quicker.
525 for i in areas.Count - 1 .. -1 .. 0 do
527 if m.Elements.Count <= area && m.State <> AreaState.Removed
530 addEdgeToQueue m.Elements
532 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
533 let nextElements = Points()
535 let mutable stop = false
537 let intensity', p = if op
= AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
538 let mutable merged = false
540 if intensity' = intensity // The intensity doesn't
change.
542 if m.Elements.Count + nextElements.Count + 1 > area
544 m.State <- AreaState.Validated
545 m.Intensity <- Some intensity
548 nextElements.Add(p) |> ignore
550 elif
if op
= AreaOperation.Opening then intensity' < intensity else intensity' > intensity
552 m.Elements.UnionWith(nextElements)
553 for e
in nextElements do
554 pixels.[e
.Y, e
.X] <- m
556 if m.Elements.Count = area
558 m.State <- AreaState.Validated
559 m.Intensity <- Some (intensity')
562 intensity <- intensity'
564 nextElements.Add(p) |> ignore
567 match pixels.[p.Y, p.X] with
570 if m'.Elements.Count + m.Elements.Count <= area
572 m'.State <- AreaState.Removed
573 for e in m'.Elements do
574 pixels.[e
.Y, e
.X] <- m
575 queue.Remove imgData.[e
.Y, e
.X, 0] e
576 addEdgeToQueue m'.Elements
577 m.Elements.UnionWith(m'.Elements)
578 let intensityMax = if op
= AreaOperation.Opening then queue.Max else queue.Min
579 if intensityMax <> intensity
581 intensity <- intensityMax
587 m.State <- AreaState.Validated
588 m.Intensity <- Some (intensity)
591 if not stop && not merged
596 let p' = Point(nj, ni)
597 if ni < 0 || ni >= h || nj < 0 || nj >= w
599 m.State <- AreaState.Validated
600 m.Intensity <- Some (intensity)
602 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
604 queue.Add (imgData.[ni, nj, 0]) p'
608 if m.Elements.Count + nextElements.Count <= area
610 m.State <- AreaState.Validated
611 m.Intensity <- Some intensity'
612 m.Elements.UnionWith(nextElements)
616 if m.State = AreaState.Validated
618 match m.Intensity with
620 for p in m.Elements do
621 imgData.[p.Y, p.X, 0] <- i
626 /// Area opening on byte image.
628 let areaOpen (img: Image<Gray, byte>) (area: int) =
629 areaOperation img area AreaOperation.Opening
632 /// Area closing on byte image.
634 let areaClose (img: Image<Gray, byte>) (area: int) =
635 areaOperation img area AreaOperation.Closing
637 // A simpler algorithm than 'areaOpen' on byte image but slower.
638 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
641 let imgData = img.Data
642 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
644 let histogram = Array.zeroCreate 256
645 for i in 0 .. h - 1 do
646 for j in 0 .. w - 1 do
647 let v = imgData.[i, j, 0] |> int
648 histogram.[v] <- histogram.[v] + 1
650 let flooded : bool[,] = Array2D.zeroCreate h w
652 let pointsChecked = HashSet<Point>()
653 let pointsToCheck = Stack<Point>()
655 for level in 255 .. -1 .. 0 do
656 let mutable n = histogram.[level]
659 for i in 0 .. h - 1 do
660 for j in 0 .. w - 1 do
661 if not flooded.[i, j] && imgData.[i, j, 0] = byte level
663 let mutable maxNeighborValue = 0uy
664 pointsChecked.Clear()
665 pointsToCheck.Clear()
666 pointsToCheck.Push(Point(j, i))
668 while pointsToCheck.Count > 0 do
669 let next = pointsToCheck.Pop()
670 pointsChecked.Add(next) |> ignore
671 flooded.[next.Y, next.X] <- true
674 let p = Point(next.X + nx, next.Y + ny)
675 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
677 let v = imgData.[p.Y, p.X, 0]
680 if not (pointsChecked.Contains(p))
682 pointsToCheck.Push(p)
683 elif v > maxNeighborValue
685 maxNeighborValue <- v
687 if int maxNeighborValue < level && pointsChecked.Count <= area
689 for p in pointsChecked do
690 imgData.[p.Y, p.X, 0] <- maxNeighborValue
693 type Island (cmp: IComparer<float32>) =
694 member val Shore = Heap.Heap<float32, Point>(cmp) with get
695 member val Level = 0.f with get, set
696 member val Surface = 0 with get, set
697 member this.IsInfinite = this.Surface = Int32.MaxValue
699 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a
) list
) (f
: ('a -> float32 -> unit) option) (op: AreaOperation) =
703 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
705 let comparer = if op = AreaOperation.Opening
706 then { new IComparer<float32> with member this.Compare(v1, v2) = v1.CompareTo(v2) }
707 else { new IComparer<float32> with member this.Compare(v1, v2) = v2.CompareTo(v1) }
709 let ownership: Island[,] = Array2D.create h w null
711 // Initialize islands with their shore.
712 let islands = List<Island>()
713 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
717 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
719 let shorePoints = Points()
721 ownership.[p.Y, p.X] <- island
725 let neighbor = Point(nj, ni)
726 if ni >= 0 && ni < h && nj >= 0 && nj < w && Object.ReferenceEquals(ownership.[ni, nj], null) && not (shorePoints.Contains(neighbor))
728 shorePoints.Add(neighbor) |> ignore
729 island.Shore.Add earth.[ni, nj, 0] neighbor
731 for area, obj in areas do
732 for island in islands do
733 let mutable stop = island.Shore.IsEmpty
735 // 'true' if 'p' is owned or adjacent to 'island'.
736 let inline ownedOrAdjacent (p: Point) : bool =
737 ownership.[p.Y, p.X] = island ||
738 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
739 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
740 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
741 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
743 while not stop && island.Surface < area do
744 let level, next = island.Shore.Max
745 let other = ownership.[next.Y, next.X]
746 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
748 island.Shore.RemoveNext ()
750 if not <| Object.ReferenceEquals(other, null)
751 then // We touching another island.
752 if island.IsInfinite || other.IsInfinite || island.Surface + other.Surface >= area || comparer.Compare(island.Level, other.Level) < 0
755 else // We can merge 'other' into 'surface
'.
756 island.Surface <- island.Surface + other.Surface
757 island.Level <- other.Level
758 // island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then other.Level else island.Level
759 for l, p in other.Shore do
760 let mutable currentY = p.Y + 1
761 while currentY < h && ownership.[currentY, p.X] = other do
762 ownership.[currentY, p.X] <- island
763 currentY <- currentY + 1
767 elif comparer.Compare(level, island.Level) > 0
771 island.Shore.RemoveNext ()
775 if ni < 0 || ni >= h || nj < 0 || nj >= w
777 island.Surface <- Int32.MaxValue
780 let neighbor = Point(nj, ni)
781 if not <| ownedOrAdjacent neighbor
783 island.Shore.Add earth.[ni, nj, 0] neighbor
786 ownership.[next.Y, next.X] <- island
787 island.Level <- level
788 island.Surface <- island.Surface + 1
790 let mutable diff = 0.f
792 for i in 0 .. h - 1 do
793 for j in 0 .. w - 1 do
794 match ownership.[i, j] with
798 diff <- diff + l - earth.[i, j, 0]
802 | Some f' -> f
' obj diff
807 /// Area opening on float image.
809 let areaOpenF (img: Image<Gray, float32>) (area: int) =
810 areaOperationF img [ area, () ] None AreaOperation.Opening
813 /// Area closing on float image.
815 let areaCloseF (img: Image<Gray, float32>) (area: int) =
816 areaOperationF img [ area, () ] None AreaOperation.Closing
819 /// Area closing on float image with different areas. Given areas must be sorted increasingly.
820 /// For each area the function 'f
' is called with the associated area value of type 'a
and the volume difference
821 /// Between the previous and the current closing.
823 let areaOpenFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
824 areaOperationF
img areas (Some f) AreaOperation.Opening
827 /// Same as 'areaOpenFWithFun' for closing operation.
829 let areaCloseFWithFun (img: Image<Gray, float32
>) (areas: (int * 'a) list) (f: 'a
-> float32
-> unit) =
830 areaOperationF
img areas (Some f) AreaOperation.Closing
833 /// Zhang and Suen thinning algorithm.
834 /// Modify 'mat' in place.
836 let thin (mat
: Matrix<byte
>) =
839 let mutable data1 = mat
.Data
840 let mutable data2 = Array2D.copy
data1
842 let mutable pixelChanged = true
843 let mutable oddIteration = true
845 while pixelChanged do
846 pixelChanged <- false
849 if data1.[i
, j] = 1uy
851 let p2 = if i
= 0 then 0uy else data1.[i
-1, j]
852 let p3 = if i
= 0 || j = w-1 then 0uy else data1.[i
-1, j+1]
853 let p4 = if j = w-1 then 0uy else data1.[i
, j+1]
854 let p5 = if i
= h-1 || j = w-1 then 0uy else data1.[i
+1, j+1]
855 let p6 = if i
= h-1 then 0uy else data1.[i
+1, j]
856 let p7 = if i
= h-1 || j = 0 then 0uy else data1.[i
+1, j-1]
857 let p8 = if j = 0 then 0uy else data1.[i
, j-1]
858 let p9 = if i
= 0 || j = 0 then 0uy else data1.[i
-1, j-1]
860 let sumNeighbors = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
861 if sumNeighbors >= 2uy && sumNeighbors <= 6uy &&
862 (if p2 = 0uy && p3 = 1uy then 1 else 0) +
863 (if p3 = 0uy && p4 = 1uy then 1 else 0) +
864 (if p4 = 0uy && p5 = 1uy then 1 else 0) +
865 (if p5 = 0uy && p6 = 1uy then 1 else 0) +
866 (if p6 = 0uy && p7 = 1uy then 1 else 0) +
867 (if p7 = 0uy && p8 = 1uy then 1 else 0) +
868 (if p8 = 0uy && p9 = 1uy then 1 else 0) +
869 (if p9 = 0uy && p2 = 1uy then 1 else 0) = 1 &&
871 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
872 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
879 oddIteration <- not oddIteration
885 /// Remove all 8-connected pixels with an area equal or greater than 'areaSize'.
886 /// Modify 'mat' in place.
888 let removeArea (mat
: Matrix<byte
>) (areaSize
: int) =
899 use mat' = new Matrix<byte>(mat.Size)
905 let data' = mat'.Data
909 if data'.[i, j] = 1uy
911 let neighborhood = List<Point>()
912 let neighborsToCheck = Stack<Point>()
913 neighborsToCheck.Push(Point(j, i))
916 while neighborsToCheck.Count > 0 do
917 let n = neighborsToCheck.Pop()
919 for (ni, nj) in neighbors do
922 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
924 neighborsToCheck.Push(Point(pj, pi))
925 data'.[pi, pj] <- 0uy
926 if neighborhood.Count <= areaSize
928 for n in neighborhood do
929 data.[n.Y, n.X] <- 0uy
931 let connectedComponents (img: Image<Gray, byte
>) (startPoints
: List<Point>) : Points =
935 let pointChecked = Points()
936 let pointToCheck = Stack<Point>(startPoints
);
940 while pointToCheck.Count > 0 do
941 let next = pointToCheck.Pop()
942 pointChecked.Add(next) |> ignore
945 if ny
<> 0 && nx
<> 0
947 let p = Point(next.X + nx
, next.Y + ny
)
948 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)
954 let drawLine (img: Image<'TColor, 'TDepth>) (color
: 'TColor) (x0: int) (y0: int) (x1: int) (y1: int) (thickness: int) =
955 img.Draw(LineSegment2D(Point(x0, y0), Point(x1, y1)), color, thickness);
957 let drawLineF (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0
: float) (y0
: float) (x1
: float) (y1
: float) (thickness
: int) =
958 img.Draw(LineSegment2DF(PointF(float32 x0
, float32 y0
), PointF(float32 x1
, float32 y1
)), color
, thickness
, CvEnum.LineType.AntiAlias);
960 let drawEllipse (img: Image<'TColor, 'TDepth>) (e
: Ellipse) (color
: 'TColor) (alpha: float) =
963 img.Draw(Emgu.CV.Structure.Ellipse(PointF(e.Cx, e.Cy), SizeF(2.f * e.B, 2.f * e.A), e.Alpha / PI * 180.f), color, 1, CvEnum.LineType.AntiAlias)
965 let windowPosX = e.Cx - e.A - 5.f
966 let gapX = windowPosX - (float32 (int windowPosX))
968 let windowPosY = e.Cy - e.A - 5.f
969 let gapY = windowPosY - (float32 (int windowPosY))
971 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e.A + 5.f) |> int, 2.f * (e.A + 5.f) |> int)
974 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
976 use i = new Image<'TColor, 'TDepth>(img.ROI.Size)
977 i.Draw(Emgu.CV.Structure.Ellipse(PointF(e.A + 5.f + gapX, e.A + 5.f + gapY), SizeF(2.f * e.B, 2.f * e.A), e.Alpha / PI * 180.f), color, 1, CvEnum.LineType.AntiAlias)
978 CvInvoke.AddWeighted(img, 1.0, i, alpha, 0.0, img)
979 img.ROI <- Rectangle.Empty
981 let drawEllipses (img: Image<'TColor, 'TDepth>) (ellipses: Ellipse list) (color: 'TColor) (alpha
: float) =
982 List.iter
(fun e
-> drawEllipse img e
color alpha
) ellipses
984 let rngCell = System.Random()
985 let drawCell (img: Image<Bgr, byte
>) (drawCellContent
: bool) (c
: Cell) =
988 let colorB = rngCell.Next(20, 70)
989 let colorG = rngCell.Next(20, 70)
990 let colorR = rngCell.Next(20, 70)
992 for y
in 0 .. c
.elements
.Height - 1 do
993 for x
in 0 .. c
.elements
.Width - 1 do
994 if c
.elements
.[y
, x
] > 0uy
996 let dx, dy
= c
.center
.X - c
.elements
.Width / 2, c
.center
.Y - c
.elements
.Height / 2
997 let b = img.Data.[y
+ dy
, x
+ dx, 0] |> int
998 let g = img.Data.[y
+ dy
, x
+ dx, 1] |> int
999 let r = img.Data.[y
+ dy
, x
+ dx, 2] |> int
1000 img.Data.[y
+ dy
, x
+ dx, 0] <- if b + colorB > 255 then 255uy else byte (b + colorB)
1001 img.Data.[y
+ dy
, x
+ dx, 1] <- if g + colorG > 255 then 255uy else byte (g + colorG)
1002 img.Data.[y
+ dy
, x
+ dx, 2] <- if r + colorR > 255 then 255uy else byte (r + colorR)
1004 let crossColor, crossColor2
=
1005 match c
.cellClass
with
1006 | HealthyRBC -> Bgr(255., 0., 0.), Bgr(255., 255., 255.)
1007 | InfectedRBC -> Bgr(0., 0., 255.), Bgr(120., 120., 255.)
1008 | Peculiar -> Bgr(0., 0., 0.), Bgr(80., 80., 80.)
1010 drawLine img crossColor2
(c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 2
1011 drawLine img crossColor2 c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 2
1013 drawLine img crossColor (c
.center
.X - 3) c
.center
.Y (c
.center
.X + 3) c
.center
.Y 1
1014 drawLine img crossColor c
.center
.X (c
.center
.Y - 3) c
.center
.X (c
.center
.Y + 3) 1
1017 let drawCells (img: Image<Bgr, byte>) (drawCellContent
: bool) (cells
: Cell list) =
1018 List.iter
(fun c
-> drawCell img drawCellContent
c) cells