dd06649785069211b8797e8edc189d3cd372d2da
[master-thesis.git] / Parasitemia / ParasitemiaCore / ImgTools.fs
1 module ParasitemiaCore.ImgTools
2
3 open System
4 open System.Drawing
5 open System.Collections.Generic
6 open System.Linq
7
8 open Emgu.CV
9 open Emgu.CV.Structure
10
11 open Heap
12 open Const
13 open Utils
14
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>()
23
24 let saveImg (img: Image<'TColor, 'TDepth>) (filepath: string) =
25 img.Save(filepath)
26
27 let saveMat (mat: Matrix<'TDepth>) (filepath: string) =
28 use img = new Image<Gray, 'TDeph>(mat.Size)
29 mat.CopyTo(img)
30 saveImg img filepath
31
32 type Histogram = { data: int[]; total: int; sum: int; min: float32; max: float32 }
33
34 let histogramImg (img: Image<Gray, float32>) (nbSamples: int) : Histogram =
35 let imgData = img.Data
36
37 let min, max =
38 let min = ref [| 0.0 |]
39 let minLocation = ref <| [| Point() |]
40 let max = ref [| 0.0 |]
41 let maxLocation = ref <| [| Point() |]
42 img.MinMax(min, max, minLocation, maxLocation)
43 float32 (!min).[0], float32 (!max).[0]
44
45 let bin (x: float32) : int =
46 let p = int ((x - min) / (max - min) * float32 nbSamples)
47 if p >= nbSamples then nbSamples - 1 else p
48
49 let data = Array.zeroCreate nbSamples
50
51 for i in 0 .. img.Height - 1 do
52 for j in 0 .. img.Width - 1 do
53 let p = bin imgData.[i, j, 0]
54 data.[p] <- data.[p] + 1
55
56 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
57
58 let histogramMat (mat: Matrix<float32>) (nbSamples: int) : Histogram =
59 let matData = mat.Data
60
61 let min, max =
62 let min = ref 0.0
63 let minLocation = ref <| Point()
64 let max = ref 0.0
65 let maxLocation = ref <| Point()
66 mat.MinMax(min, max, minLocation, maxLocation)
67 float32 !min, float32 !max
68
69 let bin (x: float32) : int =
70 let p = int ((x - min) / (max - min) * float32 nbSamples)
71 if p >= nbSamples then nbSamples - 1 else p
72
73 let data = Array.zeroCreate nbSamples
74
75 for i in 0 .. mat.Height - 1 do
76 for j in 0 .. mat.Width - 1 do
77 let p = bin matData.[i, j]
78 data.[p] <- data.[p] + 1
79
80 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
81
82 let histogram (values: float32 seq) (nbSamples: int) : Histogram =
83 let mutable min = Single.MaxValue
84 let mutable max = Single.MinValue
85 let mutable n = 0
86
87 for v in values do
88 n <- n + 1
89 if v < min then min <- v
90 if v > max then max <- v
91
92 let bin (x: float32) : int =
93 let p = int ((x - min) / (max - min) * float32 nbSamples)
94 if p >= nbSamples then nbSamples - 1 else p
95
96 let data = Array.zeroCreate nbSamples
97
98 for v in values do
99 let p = bin v
100 data.[p] <- data.[p] + 1
101
102 { data = data; total = n; sum = Array.sum data; min = min; max = max }
103
104 let otsu (hist: Histogram) : float32 * float32 * float32 =
105 let mutable sumB = 0
106 let mutable wB = 0
107 let mutable maximum = 0.0
108 let mutable level = 0
109 let sum = hist.data |> Array.mapi (fun i v -> i * v) |> Array.sum |> float
110
111 for i in 0 .. hist.data.Length - 1 do
112 wB <- wB + hist.data.[i]
113 if wB <> 0
114 then
115 let wF = hist.total - wB
116 if wF <> 0
117 then
118 sumB <- sumB + i * hist.data.[i]
119 let mB = (float sumB) / (float wB)
120 let mF = (sum - float sumB) / (float wF)
121 let between = (float wB) * (float wF) * (mB - mF) ** 2.;
122 if between >= maximum
123 then
124 level <- i
125 maximum <- between
126
127 let mean1 =
128 let mutable sum = 0
129 let mutable nb = 0
130 for i in 0 .. level - 1 do
131 sum <- sum + i * hist.data.[i]
132 nb <- nb + hist.data.[i]
133 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
134
135 let mean2 =
136 let mutable sum = 0
137 let mutable nb = 0
138 for i in level + 1 .. hist.data.Length - 1 do
139 sum <- sum + i * hist.data.[i]
140 nb <- nb + hist.data.[i]
141 (sum + level * hist.data.[level] / 2) / (nb + hist.data.[level] / 2)
142
143 let toFloat l =
144 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
145
146 toFloat level, toFloat mean1, toFloat mean2
147
148 let suppressMConnections (img: Matrix<byte>) =
149 let w = img.Width
150 let h = img.Height
151 for i in 1 .. h - 2 do
152 for j in 1 .. w - 2 do
153 if img.[i, j] > 0uy && img.Data.[i + 1, j] > 0uy && (img.Data.[i, j - 1] > 0uy && img.Data.[i - 1, j + 1] = 0uy || img.Data.[i, j + 1] > 0uy && img.Data.[i - 1, j - 1] = 0uy)
154 then
155 img.[i, j] <- 0uy
156 for i in 1 .. h - 2 do
157 for j in 1 .. w - 2 do
158 if img.[i, j] > 0uy && img.Data.[i - 1, j] > 0uy && (img.Data.[i, j - 1] > 0uy && img.Data.[i + 1, j + 1] = 0uy || img.Data.[i, j + 1] > 0uy && img.Data.[i + 1, j - 1] = 0uy)
159 then
160 img.[i, j] <- 0uy
161
162 let findEdges (img: Image<Gray, float32>) : Matrix<byte> * Image<Gray, float32> * Image<Gray, float32> =
163 let w = img.Width
164 let h = img.Height
165
166 use sobelKernel =
167 new ConvolutionKernelF(array2D [[ 1.0f; 0.0f; -1.0f ]
168 [ 2.0f; 0.0f; -2.0f ]
169 [ 1.0f; 0.0f; -1.0f ]], Point(1, 1))
170
171 let xGradient = img.Convolution(sobelKernel)
172 let yGradient = img.Convolution(sobelKernel.Transpose())
173
174 let xGradientData = xGradient.Data
175 let yGradientData = yGradient.Data
176 for r in 0 .. h - 1 do
177 xGradientData.[r, 0, 0] <- 0.f
178 xGradientData.[r, w - 1, 0] <- 0.f
179 yGradientData.[r, 0, 0] <- 0.f
180 yGradientData.[r, w - 1, 0] <- 0.f
181
182 for c in 0 .. w - 1 do
183 xGradientData.[0, c, 0] <- 0.f
184 xGradientData.[h - 1, c, 0] <- 0.f
185 yGradientData.[0, c, 0] <- 0.f
186 yGradientData.[h - 1, c, 0] <- 0.f
187
188 use magnitudes = new Matrix<float32>(xGradient.Size)
189 use angles = new Matrix<float32>(xGradient.Size)
190 CvInvoke.CartToPolar(xGradient, yGradient, magnitudes, angles) // Compute the magnitudes (without angles).
191
192 let thresholdHigh, thresholdLow =
193 let sensibilityHigh = 0.1f
194 let sensibilityLow = 0.0f
195 use magnitudesByte = magnitudes.Convert<byte>()
196 let threshold, _, _ = otsu (histogramMat magnitudes 300)
197 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
198
199 // Non-maximum suppression.
200 use nms = new Matrix<byte>(xGradient.Size)
201
202 let nmsData = nms.Data
203 let anglesData = angles.Data
204 let magnitudesData = magnitudes.Data
205 let xGradientData = xGradient.Data
206 let yGradientData = yGradient.Data
207
208 let PI = float32 Math.PI
209
210 for i in 0 .. h - 1 do
211 nmsData.[i, 0] <- 0uy
212 nmsData.[i, w - 1] <- 0uy
213
214 for j in 0 .. w - 1 do
215 nmsData.[0, j] <- 0uy
216 nmsData.[h - 1, j] <- 0uy
217
218 for i in 1 .. h - 2 do
219 for j in 1 .. w - 2 do
220 let vx = xGradientData.[i, j, 0]
221 let vy = yGradientData.[i, j, 0]
222 if vx <> 0.f || vy <> 0.f
223 then
224 let angle = anglesData.[i, j]
225
226 let vx', vy' = abs vx, abs vy
227 let ratio2 = if vx' > vy' then vy' / vx' else vx' / vy'
228 let ratio1 = 1.f - ratio2
229
230 let mNeigbors (sign: int) : float32 =
231 if angle < PI / 4.f
232 then ratio1 * magnitudesData.[i, j + sign] + ratio2 * magnitudesData.[i + sign, j + sign]
233 elif angle < PI / 2.f
234 then ratio2 * magnitudesData.[i + sign, j + sign] + ratio1 * magnitudesData.[i + sign, j]
235 elif angle < 3.f * PI / 4.f
236 then ratio1 * magnitudesData.[i + sign, j] + ratio2 * magnitudesData.[i + sign, j - sign]
237 elif angle < PI
238 then ratio2 * magnitudesData.[i + sign, j - sign] + ratio1 * magnitudesData.[i, j - sign]
239 elif angle < 5.f * PI / 4.f
240 then ratio1 * magnitudesData.[i, j - sign] + ratio2 * magnitudesData.[i - sign, j - sign]
241 elif angle < 3.f * PI / 2.f
242 then ratio2 * magnitudesData.[i - sign, j - sign] + ratio1 * magnitudesData.[i - sign, j]
243 elif angle < 7.f * PI / 4.f
244 then ratio1 * magnitudesData.[i - sign, j] + ratio2 * magnitudesData.[i - sign, j + sign]
245 else ratio2 * magnitudesData.[i - sign, j + sign] + ratio1 * magnitudesData.[i, j + sign]
246
247 let m = magnitudesData.[i, j]
248 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
249 then
250 nmsData.[i, j] <- 1uy
251
252 // suppressMConnections nms // It's not helpful for the rest of the process (ellipse detection).
253
254 let edges = new Matrix<byte>(xGradient.Size)
255 let edgesData = edges.Data
256
257 // Hysteresis thresholding.
258 let toVisit = Stack<Point>()
259 for i in 0 .. h - 1 do
260 for j in 0 .. w - 1 do
261 if nmsData.[i, j] = 1uy && magnitudesData.[i, j] >= thresholdHigh
262 then
263 nmsData.[i, j] <- 0uy
264 toVisit.Push(Point(j, i))
265 while toVisit.Count > 0 do
266 let p = toVisit.Pop()
267 edgesData.[p.Y, p.X] <- 1uy
268 for i' in -1 .. 1 do
269 for j' in -1 .. 1 do
270 if i' <> 0 || j' <> 0
271 then
272 let ni = p.Y + i'
273 let nj = p.X + j'
274 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
275 then
276 nmsData.[ni, nj] <- 0uy
277 toVisit.Push(Point(nj, ni))
278
279 edges, xGradient, yGradient
280
281 let gaussianFilter (img : Image<'TColor, 'TDepth>) (standardDeviation : float) : Image<'TColor, 'TDepth> =
282 let size = 2 * int (ceil (4.0 * standardDeviation)) + 1
283 img.SmoothGaussian(size, size, standardDeviation, standardDeviation)
284
285 type Points = HashSet<Point>
286
287 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
288 for p in points do
289 img.Data.[p.Y, p.X, 0] <- intensity
290
291 type ExtremumType =
292 | Maxima = 1
293 | Minima = 2
294
295 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
296 let w = img.Width
297 let h = img.Height
298 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
299
300 let imgData = img.Data
301 let suppress: bool[,] = Array2D.zeroCreate h w
302
303 let result = List<List<Point>>()
304
305 let flood (start: Point) : List<List<Point>> =
306 let sameLevelToCheck = Stack<Point>()
307 let betterLevelToCheck = Stack<Point>()
308 betterLevelToCheck.Push(start)
309
310 let result' = List<List<Point>>()
311
312 while betterLevelToCheck.Count > 0 do
313 let p = betterLevelToCheck.Pop()
314 if not suppress.[p.Y, p.X]
315 then
316 suppress.[p.Y, p.X] <- true
317 sameLevelToCheck.Push(p)
318 let current = List<Point>()
319
320 let mutable betterExists = false
321
322 while sameLevelToCheck.Count > 0 do
323 let p' = sameLevelToCheck.Pop()
324 let currentLevel = imgData.[p'.Y, p'.X, 0]
325 current.Add(p') |> ignore
326 for i, j in se do
327 let ni = i + p'.Y
328 let nj = j + p'.X
329 if ni >= 0 && ni < h && nj >= 0 && nj < w
330 then
331 let level = imgData.[ni, nj, 0]
332 let notSuppressed = not suppress.[ni, nj]
333
334 if level = currentLevel && notSuppressed
335 then
336 suppress.[ni, nj] <- true
337 sameLevelToCheck.Push(Point(nj, ni))
338 elif if extremumType = ExtremumType.Maxima then level > currentLevel else level < currentLevel
339 then
340 betterExists <- true
341 if notSuppressed
342 then
343 betterLevelToCheck.Push(Point(nj, ni))
344
345 if not betterExists
346 then
347 result'.Add(current)
348 result'
349
350 for i in 0 .. h - 1 do
351 for j in 0 .. w - 1 do
352 let maxima = flood (Point(j, i))
353 if maxima.Count > 0
354 then
355 result.AddRange(maxima)
356
357 result.Select(fun l -> Points(l))
358
359 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
360 findExtremum img ExtremumType.Maxima
361
362 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
363 findExtremum img ExtremumType.Minima
364
365 type PriorityQueue () =
366 let size = 256
367 let q: Points[] = Array.init size (fun i -> Points())
368 let mutable highest = -1 // Value of the first elements of 'q'.
369 let mutable lowest = size
370
371 member this.NextMax () : byte * Point =
372 if this.IsEmpty
373 then
374 invalidOp "Queue is empty"
375 else
376 let l = q.[highest]
377 let next = l.First()
378 l.Remove(next) |> ignore
379 let value = byte highest
380
381 if l.Count = 0
382 then
383 highest <- highest - 1
384 while highest > lowest && q.[highest].Count = 0 do
385 highest <- highest - 1
386 if highest = lowest
387 then
388 highest <- -1
389 lowest <- size
390
391 value, next
392
393 member this.NextMin () : byte * Point =
394 if this.IsEmpty
395 then
396 invalidOp "Queue is empty"
397 else
398 let l = q.[lowest + 1]
399 let next = l.First()
400 l.Remove(next) |> ignore
401 let value = byte (lowest + 1)
402
403 if l.Count = 0
404 then
405 lowest <- lowest + 1
406 while lowest < highest && q.[lowest + 1].Count = 0 do
407 lowest <- lowest + 1
408 if highest = lowest
409 then
410 highest <- -1
411 lowest <- size
412
413 value, next
414
415 member this.Max =
416 highest |> byte
417
418 member this.Min =
419 lowest + 1 |> byte
420
421 member this.Add (value: byte) (p: Point) =
422 let vi = int value
423
424 if vi > highest
425 then
426 highest <- vi
427 if vi <= lowest
428 then
429 lowest <- vi - 1
430
431 q.[vi].Add(p) |> ignore
432
433 member this.Remove (value: byte) (p: Point) =
434 let vi = int value
435 if q.[vi].Remove(p) && q.[vi].Count = 0
436 then
437 if vi = highest
438 then
439 highest <- highest - 1
440 while highest > lowest && q.[highest].Count = 0 do
441 highest <- highest - 1
442 elif vi - 1 = lowest
443 then
444 lowest <- lowest + 1
445 while lowest < highest && q.[lowest + 1].Count = 0 do
446 lowest <- lowest + 1
447
448 if highest = lowest // The queue is now empty.
449 then
450 highest <- -1
451 lowest <- size
452
453 member this.IsEmpty =
454 highest = -1
455
456 member this.Clear () =
457 while highest > lowest do
458 q.[highest].Clear()
459 highest <- highest - 1
460 highest <- -1
461 lowest <- size
462
463 type private AreaState =
464 | Removed = 1
465 | Unprocessed = 2
466 | Validated = 3
467
468 type private AreaOperation =
469 | Opening = 1
470 | Closing = 2
471
472 [<AllowNullLiteral>]
473 type private Area (elements: Points) =
474 member this.Elements = elements
475 member val Intensity = None with get, set
476 member val State = AreaState.Unprocessed with get, set
477
478 let private areaOperation (img: Image<Gray, byte>) (area: int) (op: AreaOperation) =
479 let w = img.Width
480 let h = img.Height
481 let imgData = img.Data
482 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
483
484 let areas = List<Area>((if op = AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map Area)
485
486 let pixels: Area[,] = Array2D.create h w null
487 for m in areas do
488 for e in m.Elements do
489 pixels.[e.Y, e.X] <- m
490
491 let queue = PriorityQueue()
492
493 let addEdgeToQueue (elements: Points) =
494 for p in elements do
495 for i, j in se do
496 let ni = i + p.Y
497 let nj = j + p.X
498 let p' = Point(nj, ni)
499 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
500 then
501 queue.Add (imgData.[ni, nj, 0]) p'
502
503 // Reverse order is quicker.
504 for i in areas.Count - 1 .. -1 .. 0 do
505 let m = areas.[i]
506 if m.Elements.Count <= area && m.State <> AreaState.Removed
507 then
508 queue.Clear()
509 addEdgeToQueue m.Elements
510
511 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
512 let nextElements = Points()
513
514 let mutable stop = false
515 while not stop do
516 let intensity', p = if op = AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
517 let mutable merged = false
518
519 if intensity' = intensity // The intensity doesn't change.
520 then
521 if m.Elements.Count + nextElements.Count + 1 > area
522 then
523 m.State <- AreaState.Validated
524 m.Intensity <- Some intensity
525 stop <- true
526 else
527 nextElements.Add(p) |> ignore
528
529 elif if op = AreaOperation.Opening then intensity' < intensity else intensity' > intensity
530 then
531 m.Elements.UnionWith(nextElements)
532 for e in nextElements do
533 pixels.[e.Y, e.X] <- m
534
535 if m.Elements.Count = area
536 then
537 m.State <- AreaState.Validated
538 m.Intensity <- Some (intensity')
539 stop <- true
540 else
541 intensity <- intensity'
542 nextElements.Clear()
543 nextElements.Add(p) |> ignore
544
545 else
546 match pixels.[p.Y, p.X] with
547 | null -> ()
548 | m' ->
549 if m'.Elements.Count + m.Elements.Count <= area
550 then
551 m'.State <- AreaState.Removed
552 for e in m'.Elements do
553 pixels.[e.Y, e.X] <- m
554 queue.Remove imgData.[e.Y, e.X, 0] e
555 addEdgeToQueue m'.Elements
556 m.Elements.UnionWith(m'.Elements)
557 let intensityMax = if op = AreaOperation.Opening then queue.Max else queue.Min
558 if intensityMax <> intensity
559 then
560 intensity <- intensityMax
561 nextElements.Clear()
562 merged <- true
563
564 if not merged
565 then
566 m.State <- AreaState.Validated
567 m.Intensity <- Some (intensity)
568 stop <- true
569
570 if not stop && not merged
571 then
572 for i, j in se do
573 let ni = i + p.Y
574 let nj = j + p.X
575 let p' = Point(nj, ni)
576 if ni < 0 || ni >= h || nj < 0 || nj >= w
577 then
578 m.State <- AreaState.Validated
579 m.Intensity <- Some (intensity)
580 stop <- true
581 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
582 then
583 queue.Add (imgData.[ni, nj, 0]) p'
584
585 if queue.IsEmpty
586 then
587 if m.Elements.Count + nextElements.Count <= area
588 then
589 m.State <- AreaState.Validated
590 m.Intensity <- Some intensity'
591 m.Elements.UnionWith(nextElements)
592 stop <- true
593
594 for m in areas do
595 if m.State = AreaState.Validated
596 then
597 match m.Intensity with
598 | Some i ->
599 for p in m.Elements do
600 imgData.[p.Y, p.X, 0] <- i
601 | _ -> ()
602 ()
603
604 let areaOpen (img: Image<Gray, byte>) (area: int) =
605 areaOperation img area AreaOperation.Opening
606
607 let areaClose (img: Image<Gray, byte>) (area: int) =
608 areaOperation img area AreaOperation.Closing
609
610 [<AllowNullLiteral>]
611 type Island (cmp: IComparer<float32>) =
612 member val Shore = Heap.Heap<float32, Point>(cmp) with get
613 member val Level = 0.f with get, set
614 member val Surface = 0 with get, set
615
616 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a) list) (f: ('a -> float32 -> unit) option) (op: AreaOperation) =
617 let w = img.Width
618 let h = img.Height
619 let earth = img.Data
620 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
621
622 let comparer = if op = AreaOperation.Opening
623 then { new IComparer<float32> with member this.Compare(v1, v2) = v1.CompareTo(v2) }
624 else { new IComparer<float32> with member this.Compare(v1, v2) = v2.CompareTo(v1) }
625
626 let ownership: Island[,] = Array2D.create h w null
627
628 // Initialize islands with their shore.
629 let islands = List<Island>()
630 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
631 for e in extremum do
632 let island =
633 let p = e.First()
634 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
635 islands.Add(island)
636 let shorePoints = Points()
637 for p in e do
638 ownership.[p.Y, p.X] <- island
639 for i, j in se do
640 let ni = i + p.Y
641 let nj = j + p.X
642 let neighbor = Point(nj, ni)
643 if ni >= 0 && ni < h && nj >= 0 && nj < w && Object.ReferenceEquals(ownership.[ni, nj], null) && not (shorePoints.Contains(neighbor))
644 then
645 shorePoints.Add(neighbor) |> ignore
646 island.Shore.Add earth.[ni, nj, 0] neighbor
647
648 for area, obj in areas do
649 for island in islands do
650 let mutable stop = island.Shore.IsEmpty
651
652 // 'true' if 'p' is owned or adjacent to 'island'.
653 let inline ownedOrAdjacent (p: Point) : bool =
654 ownership.[p.Y, p.X] = island ||
655 (p.Y > 0 && ownership.[p.Y - 1, p.X] = island) ||
656 (p.Y < h - 1 && ownership.[p.Y + 1, p.X] = island) ||
657 (p.X > 0 && ownership.[p.Y, p.X - 1] = island) ||
658 (p.X < w - 1 && ownership.[p.Y, p.X + 1] = island)
659
660 while not stop && island.Surface < area do
661 let level, next = island.Shore.Max
662 let other = ownership.[next.Y, next.X]
663 if other = island // During merging, some points on the shore may be owned by the island itself -> ignored.
664 then
665 island.Shore.RemoveNext ()
666 else
667 if not <| Object.ReferenceEquals(other, null)
668 then // We touching another island.
669 if island.Surface + other.Surface >= area
670 then
671 stop <- true
672 else // We can merge 'other' into 'surface'.
673 island.Surface <- island.Surface + other.Surface
674 island.Level <- if comparer.Compare(island.Level, other.Level) > 0 then island.Level else other.Level
675 for l, p in other.Shore do
676 let mutable currentY = p.Y + 1
677 while currentY < h && ownership.[currentY, p.X] = other do
678 ownership.[currentY, p.X] <- island
679 currentY <- currentY + 1
680 island.Shore.Add l p
681 other.Shore.Clear()
682
683 elif comparer.Compare(level, island.Level) > 0
684 then
685 stop <- true
686 else
687 island.Shore.RemoveNext ()
688 for i, j in se do
689 let ni = i + next.Y
690 let nj = j + next.X
691 if ni < 0 || ni >= h || nj < 0 || nj >= w
692 then
693 island.Surface <- Int32.MaxValue
694 stop <- true
695 else
696 let neighbor = Point(nj, ni)
697 if not <| ownedOrAdjacent neighbor
698 then
699 island.Shore.Add earth.[ni, nj, 0] neighbor
700 if not stop
701 then
702 ownership.[next.Y, next.X] <- island
703 island.Level <- level
704 island.Surface <- island.Surface + 1
705
706 let mutable diff = 0.f
707
708 for i in 0 .. h - 1 do
709 for j in 0 .. w - 1 do
710 match ownership.[i, j] with
711 | null -> ()
712 | island ->
713 let l = island.Level
714 diff <- diff + l - earth.[i, j, 0]
715 earth.[i, j, 0] <- l
716
717 match f with
718 | Some f' -> f' obj diff
719 | _ -> ()
720 ()
721
722 let areaOpenF (img: Image<Gray, float32>) (area: int) =
723 areaOperationF img [ area, () ] None AreaOperation.Opening
724
725 let areaCloseF (img: Image<Gray, float32>) (area: int) =
726 areaOperationF img [ area, () ] None AreaOperation.Closing
727
728 let areaOpenFWithFun (img: Image<Gray, float32>) (areas: (int * 'a) list) (f: 'a -> float32 -> unit) =
729 areaOperationF img areas (Some f) AreaOperation.Opening
730
731 let areaCloseFWithFun (img: Image<Gray, float32>) (areas: (int * 'a) list) (f: 'a -> float32 -> unit) =
732 areaOperationF img areas (Some f) AreaOperation.Closing
733
734 // A simpler algorithm than 'areaOpen' but slower.
735 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
736 let w = img.Width
737 let h = img.Height
738 let imgData = img.Data
739 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
740
741 let histogram = Array.zeroCreate 256
742 for i in 0 .. h - 1 do
743 for j in 0 .. w - 1 do
744 let v = imgData.[i, j, 0] |> int
745 histogram.[v] <- histogram.[v] + 1
746
747 let flooded : bool[,] = Array2D.zeroCreate h w
748
749 let pointsChecked = HashSet<Point>()
750 let pointsToCheck = Stack<Point>()
751
752 for level in 255 .. -1 .. 0 do
753 let mutable n = histogram.[level]
754 if n > 0
755 then
756 for i in 0 .. h - 1 do
757 for j in 0 .. w - 1 do
758 if not flooded.[i, j] && imgData.[i, j, 0] = byte level
759 then
760 let mutable maxNeighborValue = 0uy
761 pointsChecked.Clear()
762 pointsToCheck.Clear()
763 pointsToCheck.Push(Point(j, i))
764
765 while pointsToCheck.Count > 0 do
766 let next = pointsToCheck.Pop()
767 pointsChecked.Add(next) |> ignore
768 flooded.[next.Y, next.X] <- true
769
770 for nx, ny in se do
771 let p = Point(next.X + nx, next.Y + ny)
772 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
773 then
774 let v = imgData.[p.Y, p.X, 0]
775 if v = byte level
776 then
777 if not (pointsChecked.Contains(p))
778 then
779 pointsToCheck.Push(p)
780 elif v > maxNeighborValue
781 then
782 maxNeighborValue <- v
783
784 if int maxNeighborValue < level && pointsChecked.Count <= area
785 then
786 for p in pointsChecked do
787 imgData.[p.Y, p.X, 0] <- maxNeighborValue
788
789 // Zhang and Suen algorithm.
790 // Modify 'mat' in place.
791 let thin (mat: Matrix<byte>) =
792 let w = mat.Width
793 let h = mat.Height
794 let mutable data1 = mat.Data
795 let mutable data2 = Array2D.copy data1
796
797 let mutable pixelChanged = true
798 let mutable oddIteration = true
799
800 while pixelChanged do
801 pixelChanged <- false
802 for i in 0..h-1 do
803 for j in 0..w-1 do
804 if data1.[i, j] = 1uy
805 then
806 let p2 = if i = 0 then 0uy else data1.[i-1, j]
807 let p3 = if i = 0 || j = w-1 then 0uy else data1.[i-1, j+1]
808 let p4 = if j = w-1 then 0uy else data1.[i, j+1]
809 let p5 = if i = h-1 || j = w-1 then 0uy else data1.[i+1, j+1]
810 let p6 = if i = h-1 then 0uy else data1.[i+1, j]
811 let p7 = if i = h-1 || j = 0 then 0uy else data1.[i+1, j-1]
812 let p8 = if j = 0 then 0uy else data1.[i, j-1]
813 let p9 = if i = 0 || j = 0 then 0uy else data1.[i-1, j-1]
814
815 let sumNeighbors = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
816 if sumNeighbors >= 2uy && sumNeighbors <= 6uy &&
817 (if p2 = 0uy && p3 = 1uy then 1 else 0) +
818 (if p3 = 0uy && p4 = 1uy then 1 else 0) +
819 (if p4 = 0uy && p5 = 1uy then 1 else 0) +
820 (if p5 = 0uy && p6 = 1uy then 1 else 0) +
821 (if p6 = 0uy && p7 = 1uy then 1 else 0) +
822 (if p7 = 0uy && p8 = 1uy then 1 else 0) +
823 (if p8 = 0uy && p9 = 1uy then 1 else 0) +
824 (if p9 = 0uy && p2 = 1uy then 1 else 0) = 1 &&
825 if oddIteration
826 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
827 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
828 then
829 data2.[i, j] <- 0uy
830 pixelChanged <- true
831 else
832 data2.[i, j] <- 0uy
833
834 oddIteration <- not oddIteration
835 let tmp = data1
836 data1 <- data2
837 data2 <- tmp
838
839 // Remove all 8-connected pixels with an area equal or greater than 'areaSize'.
840 // Modify 'mat' in place.
841 let removeArea (mat: Matrix<byte>) (areaSize: int) =
842 let neighbors = [|
843 (-1, 0) // p2
844 (-1, 1) // p3
845 ( 0, 1) // p4
846 ( 1, 1) // p5
847 ( 1, 0) // p6
848 ( 1, -1) // p7
849 ( 0, -1) // p8
850 (-1, -1) |] // p9
851
852 use mat' = new Matrix<byte>(mat.Size)
853 let w = mat'.Width
854 let h = mat'.Height
855 mat.CopyTo(mat')
856
857 let data = mat.Data
858 let data' = mat'.Data
859
860 for i in 0..h-1 do
861 for j in 0..w-1 do
862 if data'.[i, j] = 1uy
863 then
864 let neighborhood = List<Point>()
865 let neighborsToCheck = Stack<Point>()
866 neighborsToCheck.Push(Point(j, i))
867 data'.[i, j] <- 0uy
868
869 while neighborsToCheck.Count > 0 do
870 let n = neighborsToCheck.Pop()
871 neighborhood.Add(n)
872 for (ni, nj) in neighbors do
873 let pi = n.Y + ni
874 let pj = n.X + nj
875 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
876 then
877 neighborsToCheck.Push(Point(pj, pi))
878 data'.[pi, pj] <- 0uy
879 if neighborhood.Count <= areaSize
880 then
881 for n in neighborhood do
882 data.[n.Y, n.X] <- 0uy
883
884 let connectedComponents (img: Image<Gray, byte>) (startPoints: List<Point>) : List<Point> =
885 let w = img.Width
886 let h = img.Height
887
888 let pointChecked = Points()
889 let pointToCheck = Stack<Point>(startPoints);
890
891 let data = img.Data
892
893 while pointToCheck.Count > 0 do
894 let next = pointToCheck.Pop()
895 pointChecked.Add(next) |> ignore
896 for ny in -1 .. 1 do
897 for nx in -1 .. 1 do
898 if ny <> 0 && nx <> 0
899 then
900 let p = Point(next.X + nx, next.Y + ny)
901 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h && data.[p.Y, p.X, 0] > 0uy && not (pointChecked.Contains p)
902 then
903 pointToCheck.Push(p)
904
905 List<Point>(pointChecked)
906
907 let drawLine (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0: int) (y0: int) (x1: int) (y1: int) (thickness: int) =
908 img.Draw(LineSegment2D(Point(x0, y0), Point(x1, y1)), color, thickness);
909
910 let drawLineF (img: Image<'TColor, 'TDepth>) (color: 'TColor) (x0: float) (y0: float) (x1: float) (y1: float) (thickness: int) =
911 img.Draw(LineSegment2DF(PointF(float32 x0, float32 y0), PointF(float32 x1, float32 y1)), color, thickness, CvEnum.LineType.AntiAlias);
912
913 let drawEllipse (img: Image<'TColor, 'TDepth>) (e: Types.Ellipse) (color: 'TColor) (alpha: float) =
914 if alpha >= 1.0
915 then
916 img.Draw(Ellipse(PointF(float32 e.Cx, float32 e.Cy), SizeF(2.f * e.B, 2.f * e.A), e.Alpha / PI * 180.f), color, 1, CvEnum.LineType.AntiAlias)
917 else
918 let windowPosX = e.Cx - e.A - 5.f
919 let gapX = windowPosX - (float32 (int windowPosX))
920
921 let windowPosY = e.Cy - e.A - 5.f
922 let gapY = windowPosY - (float32 (int windowPosY))
923
924 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e.A + 5.f) |> int, 2.f * (e.A + 5.f) |> int)
925
926 img.ROI <- roi
927 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
928 then
929 use i = new Image<'TColor, 'TDepth>(img.ROI.Size)
930 i.Draw(Ellipse(PointF(float32 <| (e.A + 5.f + gapX) , float32 <| (e.A + 5.f + gapY)), SizeF(2.f * e.B, 2.f * e.A), e.Alpha / PI * 180.f), color, 1, CvEnum.LineType.AntiAlias)
931 CvInvoke.AddWeighted(img, 1.0, i, alpha, 0.0, img)
932 img.ROI <- Rectangle.Empty
933
934 let drawEllipses (img: Image<'TColor, 'TDepth>) (ellipses: Types.Ellipse list) (color: 'TColor) (alpha: float) =
935 List.iter (fun e -> drawEllipse img e color alpha) ellipses
936
937 let rngCell = System.Random()
938 let drawCell (img: Image<Bgr, byte>) (drawCellContent: bool) (c: Types.Cell) =
939 if drawCellContent
940 then
941 let colorB = rngCell.Next(20, 70)
942 let colorG = rngCell.Next(20, 70)
943 let colorR = rngCell.Next(20, 70)
944
945 for y in 0 .. c.elements.Height - 1 do
946 for x in 0 .. c.elements.Width - 1 do
947 if c.elements.[y, x] > 0uy
948 then
949 let dx, dy = c.center.X - c.elements.Width / 2, c.center.Y - c.elements.Height / 2
950 let b = img.Data.[y + dy, x + dx, 0] |> int
951 let g = img.Data.[y + dy, x + dx, 1] |> int
952 let r = img.Data.[y + dy, x + dx, 2] |> int
953 img.Data.[y + dy, x + dx, 0] <- if b + colorB > 255 then 255uy else byte (b + colorB)
954 img.Data.[y + dy, x + dx, 1] <- if g + colorG > 255 then 255uy else byte (g + colorG)
955 img.Data.[y + dy, x + dx, 2] <- if r + colorR > 255 then 255uy else byte (r + colorR)
956
957 let crossColor, crossColor2 =
958 match c.cellClass with
959 | Types.HealthyRBC -> Bgr(255., 0., 0.), Bgr(255., 255., 255.)
960 | Types.InfectedRBC -> Bgr(0., 0., 255.), Bgr(120., 120., 255.)
961 | Types.Peculiar -> Bgr(0., 0., 0.), Bgr(80., 80., 80.)
962
963 drawLine img crossColor2 (c.center.X - 3) c.center.Y (c.center.X + 3) c.center.Y 2
964 drawLine img crossColor2 c.center.X (c.center.Y - 3) c.center.X (c.center.Y + 3) 2
965
966 drawLine img crossColor (c.center.X - 3) c.center.Y (c.center.X + 3) c.center.Y 1
967 drawLine img crossColor c.center.X (c.center.Y - 3) c.center.X (c.center.Y + 3) 1
968
969
970 let drawCells (img: Image<Bgr, byte>) (drawCellContent: bool) (cells: Types.Cell list) =
971 List.iter (fun c -> drawCell img drawCellContent c) cells