* Add an exact method to compute an ellipse from three points and two tangents.
[master-thesis.git] / Parasitemia / Parasitemia / ImgTools.fs
1 module 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
25 let saveImg (img: Image<'TColor, 'TDepth>) (filepath: string) =
26 img.Save(filepath)
27
28
29 let saveMat (mat: Matrix<'TDepth>) (filepath: string) =
30 use img = new Image<Gray, 'TDeph>(mat.Size)
31 mat.CopyTo(img)
32 saveImg img filepath
33
34 type Histogram = { data: int[]; total: int; sum: int; min: float32; max: float32 }
35
36 let histogramImg (img: Image<Gray, float32>) (nbSamples: int) : Histogram =
37 let imgData = img.Data
38
39 let min, max =
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]
46
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
50
51 let data = Array.zeroCreate nbSamples
52
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
57
58 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
59
60 let histogramMat (mat: Matrix<float32>) (nbSamples: int) : Histogram =
61 let matData = mat.Data
62
63 let min, max =
64 let min = ref 0.0
65 let minLocation = ref <| Point()
66 let max = ref 0.0
67 let maxLocation = ref <| Point()
68 mat.MinMax(min, max, minLocation, maxLocation)
69 float32 !min, float32 !max
70
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
74
75 let data = Array.zeroCreate nbSamples
76
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
81
82 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
83
84 let histogram (values: float32 seq) (nbSamples: int) : Histogram =
85 let mutable min = Single.MaxValue
86 let mutable max = Single.MinValue
87 let mutable n = 0
88
89 for v in values do
90 n <- n + 1
91 if v < min then min <- v
92 if v > max then max <- v
93
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
97
98 let data = Array.zeroCreate nbSamples
99
100 for v in values do
101 let p = bin v
102 data.[p] <- data.[p] + 1
103
104 { data = data; total = n; sum = Array.sum data; min = min; max = max }
105
106 let otsu (hist: Histogram) : float32 * float32 * float32 =
107 let mutable sumB = 0
108 let mutable wB = 0
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
112
113 for i in 0 .. hist.data.Length - 1 do
114 wB <- wB + hist.data.[i]
115 if wB <> 0
116 then
117 let wF = hist.total - wB
118 if wF <> 0
119 then
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
125 then
126 level <- i
127 maximum <- between
128
129 let mean1 =
130 let mutable sum = 0
131 let mutable nb = 0
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)
136
137 let mean2 =
138 let mutable sum = 0
139 let mutable nb = 0
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)
144
145 let toFloat l =
146 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
147
148 toFloat level, toFloat mean1, toFloat mean2
149
150 let suppressMConnections (img: Matrix<byte>) =
151 let w = img.Width
152 let h = img.Height
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)
156 then
157 img.[i, j] <- 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)
161 then
162 img.[i, j] <- 0uy
163
164 let findEdges (img: Image<Gray, float32>) : Matrix<byte> * Image<Gray, float32> * Image<Gray, float32> =
165 let w = img.Width
166 let h = img.Height
167
168 use sobelKernel =
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))
172
173 let xGradient = img.Convolution(sobelKernel)
174 let yGradient = img.Convolution(sobelKernel.Transpose())
175
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
183
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
189
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).
193
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)
200
201 // Non-maximum suppression.
202 use nms = new Matrix<byte>(xGradient.Size)
203
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
209
210 let PI = float32 Math.PI
211
212 for i in 0 .. h - 1 do
213 nmsData.[i, 0] <- 0uy
214 nmsData.[i, w - 1] <- 0uy
215
216 for j in 0 .. w - 1 do
217 nmsData.[0, j] <- 0uy
218 nmsData.[h - 1, j] <- 0uy
219
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
225 then
226 let angle = anglesData.[i, j]
227
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
231
232 let mNeigbors (sign: int) : float32 =
233 if angle < PI / 4.f
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]
239 elif angle < PI
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]
248
249 let m = magnitudesData.[i, j]
250 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
251 then
252 nmsData.[i, j] <- 1uy
253
254 // suppressMConnections nms // It's not helpful for the rest of the process (ellipse detection).
255
256 let edges = new Matrix<byte>(xGradient.Size)
257 let edgesData = edges.Data
258
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
264 then
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
270 for i' in -1 .. 1 do
271 for j' in -1 .. 1 do
272 if i' <> 0 || j' <> 0
273 then
274 let ni = p.Y + i'
275 let nj = p.X + j'
276 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
277 then
278 nmsData.[ni, nj] <- 0uy
279 toVisit.Push(Point(nj, ni))
280
281 edges, xGradient, yGradient
282
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)
286
287 type Points = HashSet<Point>
288
289 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
290 for p in points do
291 img.Data.[p.Y, p.X, 0] <- intensity
292
293 type ExtremumType =
294 | Maxima = 1
295 | Minima = 2
296
297 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
298 let w = img.Width
299 let h = img.Height
300 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
301
302 let imgData = img.Data
303 let suppress: bool[,] = Array2D.zeroCreate h w
304
305 let result = List<List<Point>>()
306
307 let flood (start: Point) : List<List<Point>> =
308 let sameLevelToCheck = Stack<Point>()
309 let betterLevelToCheck = Stack<Point>()
310 betterLevelToCheck.Push(start)
311
312 let result' = List<List<Point>>()
313
314 while betterLevelToCheck.Count > 0 do
315 let p = betterLevelToCheck.Pop()
316 if not suppress.[p.Y, p.X]
317 then
318 suppress.[p.Y, p.X] <- true
319 sameLevelToCheck.Push(p)
320 let current = List<Point>()
321
322 let mutable betterExists = false
323
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
328 for i, j in se do
329 let ni = i + p'.Y
330 let nj = j + p'.X
331 if ni >= 0 && ni < h && nj >= 0 && nj < w
332 then
333 let level = imgData.[ni, nj, 0]
334 let notSuppressed = not suppress.[ni, nj]
335
336 if level = currentLevel && notSuppressed
337 then
338 suppress.[ni, nj] <- true
339 sameLevelToCheck.Push(Point(nj, ni))
340 elif if extremumType = ExtremumType.Maxima then level > currentLevel else level < currentLevel
341 then
342 betterExists <- true
343 if notSuppressed
344 then
345 betterLevelToCheck.Push(Point(nj, ni))
346
347 if not betterExists
348 then
349 result'.Add(current)
350 result'
351
352 for i in 0 .. h - 1 do
353 for j in 0 .. w - 1 do
354 let maxima = flood (Point(j, i))
355 if maxima.Count > 0
356 then
357 result.AddRange(maxima)
358
359 result.Select(fun l -> Points(l))
360
361 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
362 findExtremum img ExtremumType.Maxima
363
364 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
365 findExtremum img ExtremumType.Minima
366
367 type PriorityQueue () =
368 let size = 256
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
372
373 member this.NextMax () : byte * Point =
374 if this.IsEmpty
375 then
376 invalidOp "Queue is empty"
377 else
378 let l = q.[highest]
379 let next = l.First()
380 l.Remove(next) |> ignore
381 let value = byte highest
382
383 if l.Count = 0
384 then
385 highest <- highest - 1
386 while highest > lowest && q.[highest].Count = 0 do
387 highest <- highest - 1
388 if highest = lowest
389 then
390 highest <- -1
391 lowest <- size
392
393 value, next
394
395 member this.NextMin () : byte * Point =
396 if this.IsEmpty
397 then
398 invalidOp "Queue is empty"
399 else
400 let l = q.[lowest + 1]
401 let next = l.First()
402 l.Remove(next) |> ignore
403 let value = byte (lowest + 1)
404
405 if l.Count = 0
406 then
407 lowest <- lowest + 1
408 while lowest < highest && q.[lowest + 1].Count = 0 do
409 lowest <- lowest + 1
410 if highest = lowest
411 then
412 highest <- -1
413 lowest <- size
414
415 value, next
416
417 member this.Max =
418 highest |> byte
419
420 member this.Min =
421 lowest + 1 |> byte
422
423 member this.Add (value: byte) (p: Point) =
424 let vi = int value
425
426 if vi > highest
427 then
428 highest <- vi
429 if vi <= lowest
430 then
431 lowest <- vi - 1
432
433 q.[vi].Add(p) |> ignore
434
435 member this.Remove (value: byte) (p: Point) =
436 let vi = int value
437 if q.[vi].Remove(p) && q.[vi].Count = 0
438 then
439 if vi = highest
440 then
441 highest <- highest - 1
442 while highest > lowest && q.[highest].Count = 0 do
443 highest <- highest - 1
444 elif vi - 1 = lowest
445 then
446 lowest <- lowest + 1
447 while lowest < highest && q.[lowest + 1].Count = 0 do
448 lowest <- lowest + 1
449
450 if highest = lowest // The queue is now empty.
451 then
452 highest <- -1
453 lowest <- size
454
455 member this.IsEmpty =
456 highest = -1
457
458 member this.Clear () =
459 while highest > lowest do
460 q.[highest].Clear()
461 highest <- highest - 1
462 highest <- -1
463 lowest <- size
464
465 type private AreaState =
466 | Removed = 1
467 | Unprocessed = 2
468 | Validated = 3
469
470 type private AreaOperation =
471 | Opening = 1
472 | Closing = 2
473
474 [<AllowNullLiteral>]
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
479
480 let private areaOperation (img: Image<Gray, byte>) (area: int) (op: AreaOperation) =
481 let w = img.Width
482 let h = img.Height
483 let imgData = img.Data
484 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
485
486 let areas = List<Area>((if op = AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map Area)
487
488 let pixels: Area[,] = Array2D.create h w null
489 for m in areas do
490 for e in m.Elements do
491 pixels.[e.Y, e.X] <- m
492
493 let queue = PriorityQueue()
494
495 let addEdgeToQueue (elements: Points) =
496 for p in elements do
497 for i, j in se do
498 let ni = i + p.Y
499 let nj = j + p.X
500 let p' = Point(nj, ni)
501 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
502 then
503 queue.Add (imgData.[ni, nj, 0]) p'
504
505 // Reverse order is quicker.
506 for i in areas.Count - 1 .. -1 .. 0 do
507 let m = areas.[i]
508 if m.Elements.Count <= area && m.State <> AreaState.Removed
509 then
510 queue.Clear()
511 addEdgeToQueue m.Elements
512
513 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
514 let nextElements = Points()
515
516 let mutable stop = false
517 while not stop do
518 let intensity', p = if op = AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
519 let mutable merged = false
520
521 if intensity' = intensity // The intensity doesn't change.
522 then
523 if m.Elements.Count + nextElements.Count + 1 > area
524 then
525 m.State <- AreaState.Validated
526 m.Intensity <- Some intensity
527 stop <- true
528 else
529 nextElements.Add(p) |> ignore
530
531 elif if op = AreaOperation.Opening then intensity' < intensity else intensity' > intensity
532 then
533 m.Elements.UnionWith(nextElements)
534 for e in nextElements do
535 pixels.[e.Y, e.X] <- m
536
537 if m.Elements.Count = area
538 then
539 m.State <- AreaState.Validated
540 m.Intensity <- Some (intensity')
541 stop <- true
542 else
543 intensity <- intensity'
544 nextElements.Clear()
545 nextElements.Add(p) |> ignore
546
547 else
548 match pixels.[p.Y, p.X] with
549 | null -> ()
550 | m' ->
551 if m'.Elements.Count + m.Elements.Count <= area
552 then
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
561 then
562 intensity <- intensityMax
563 nextElements.Clear()
564 merged <- true
565
566 if not merged
567 then
568 m.State <- AreaState.Validated
569 m.Intensity <- Some (intensity)
570 stop <- true
571
572 if not stop && not merged
573 then
574 for i, j in se do
575 let ni = i + p.Y
576 let nj = j + p.X
577 let p' = Point(nj, ni)
578 if ni < 0 || ni >= h || nj < 0 || nj >= w
579 then
580 m.State <- AreaState.Validated
581 m.Intensity <- Some (intensity)
582 stop <- true
583 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
584 then
585 queue.Add (imgData.[ni, nj, 0]) p'
586
587 if queue.IsEmpty
588 then
589 if m.Elements.Count + nextElements.Count <= area
590 then
591 m.State <- AreaState.Validated
592 m.Intensity <- Some intensity'
593 m.Elements.UnionWith(nextElements)
594 stop <- true
595
596 for m in areas do
597 if m.State = AreaState.Validated
598 then
599 match m.Intensity with
600 | Some i ->
601 for p in m.Elements do
602 imgData.[p.Y, p.X, 0] <- i
603 | _ -> ()
604 ()
605
606 let areaOpen (img: Image<Gray, byte>) (area: int) =
607 areaOperation img area AreaOperation.Opening
608
609 let areaClose (img: Image<Gray, byte>) (area: int) =
610 areaOperation img area AreaOperation.Closing
611
612 [<AllowNullLiteral>]
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
617
618 let private areaOperationF (img: Image<Gray, float32>) (areas: (int * 'a) list) (f: ('a -> float32 -> unit) option) (op: AreaOperation) =
619 let w = img.Width
620 let h = img.Height
621 let earth = img.Data
622 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
623
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) }
627
628 let ownership: Island[,] = Array2D.create h w null
629
630 // Initialize islands with their shore.
631 let islands = List<Island>()
632 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
633 for e in extremum do
634 let island =
635 let p = e.First()
636 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
637 islands.Add(island)
638 let shorePoints = Points()
639 for p in e do
640 ownership.[p.Y, p.X] <- island
641 for i, j in se do
642 let ni = i + p.Y
643 let nj = j + p.X
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))
646 then
647 shorePoints.Add(neighbor) |> ignore
648 island.Shore.Add earth.[ni, nj, 0] neighbor
649
650 for area, obj in areas do
651 for island in islands do
652 let mutable stop = island.Shore.IsEmpty
653
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)
661
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.
666 then
667 island.Shore.RemoveNext ()
668 else
669 if not <| Object.ReferenceEquals(other, null)
670 then // We touching another island.
671 if island.Surface + other.Surface >= area
672 then
673 stop <- true
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
682 island.Shore.Add l p
683 other.Shore.Clear()
684
685 elif comparer.Compare(level, island.Level) > 0
686 then
687 stop <- true
688 else
689 island.Shore.RemoveNext ()
690 for i, j in se do
691 let ni = i + next.Y
692 let nj = j + next.X
693 if ni < 0 || ni >= h || nj < 0 || nj >= w
694 then
695 island.Surface <- Int32.MaxValue
696 stop <- true
697 else
698 let neighbor = Point(nj, ni)
699 if not <| ownedOrAdjacent neighbor
700 then
701 island.Shore.Add earth.[ni, nj, 0] neighbor
702 if not stop
703 then
704 ownership.[next.Y, next.X] <- island
705 island.Level <- level
706 island.Surface <- island.Surface + 1
707
708 let mutable diff = 0.f
709
710 for i in 0 .. h - 1 do
711 for j in 0 .. w - 1 do
712 match ownership.[i, j] with
713 | null -> ()
714 | island ->
715 let l = island.Level
716 diff <- diff + l - earth.[i, j, 0]
717 earth.[i, j, 0] <- l
718
719 match f with
720 | Some f' -> f' obj diff
721 | _ -> ()
722 ()
723
724 let areaOpenF (img: Image<Gray, float32>) (area: int) =
725 areaOperationF img [ area, () ] None AreaOperation.Opening
726
727 let areaCloseF (img: Image<Gray, float32>) (area: int) =
728 areaOperationF img [ area, () ] None AreaOperation.Closing
729
730 let areaOpenFWithFun (img: Image<Gray, float32>) (areas: (int * 'a) list) (f: 'a -> float32 -> unit) =
731 areaOperationF img areas (Some f) AreaOperation.Opening
732
733 let areaCloseFWithFun (img: Image<Gray, float32>) (areas: (int * 'a) list) (f: 'a -> float32 -> unit) =
734 areaOperationF img areas (Some f) AreaOperation.Closing
735
736 // A simpler algorithm than 'areaOpen' but slower.
737 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
738 let w = img.Width
739 let h = img.Height
740 let imgData = img.Data
741 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
742
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
748
749 let flooded : bool[,] = Array2D.zeroCreate h w
750
751 let pointsChecked = HashSet<Point>()
752 let pointsToCheck = Stack<Point>()
753
754 for level in 255 .. -1 .. 0 do
755 let mutable n = histogram.[level]
756 if n > 0
757 then
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
761 then
762 let mutable maxNeighborValue = 0uy
763 pointsChecked.Clear()
764 pointsToCheck.Clear()
765 pointsToCheck.Push(Point(j, i))
766
767 while pointsToCheck.Count > 0 do
768 let next = pointsToCheck.Pop()
769 pointsChecked.Add(next) |> ignore
770 flooded.[next.Y, next.X] <- true
771
772 for nx, ny in se do
773 let p = Point(next.X + nx, next.Y + ny)
774 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
775 then
776 let v = imgData.[p.Y, p.X, 0]
777 if v = byte level
778 then
779 if not (pointsChecked.Contains(p))
780 then
781 pointsToCheck.Push(p)
782 elif v > maxNeighborValue
783 then
784 maxNeighborValue <- v
785
786 if int maxNeighborValue < level && pointsChecked.Count <= area
787 then
788 for p in pointsChecked do
789 imgData.[p.Y, p.X, 0] <- maxNeighborValue
790
791 // Zhang and Suen algorithm.
792 // Modify 'mat' in place.
793 let thin (mat: Matrix<byte>) =
794 let w = mat.Width
795 let h = mat.Height
796 let mutable data1 = mat.Data
797 let mutable data2 = Array2D.copy data1
798
799 let mutable pixelChanged = true
800 let mutable oddIteration = true
801
802 while pixelChanged do
803 pixelChanged <- false
804 for i in 0..h-1 do
805 for j in 0..w-1 do
806 if data1.[i, j] = 1uy
807 then
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]
816
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 &&
827 if oddIteration
828 then p2 * p4 * p6 = 0uy && p4 * p6 * p8 = 0uy
829 else p2 * p4 * p8 = 0uy && p2 * p6 * p8 = 0uy
830 then
831 data2.[i, j] <- 0uy
832 pixelChanged <- true
833 else
834 data2.[i, j] <- 0uy
835
836 oddIteration <- not oddIteration
837 let tmp = data1
838 data1 <- data2
839 data2 <- tmp
840
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) =
844 let neighbors = [|
845 (-1, 0) // p2
846 (-1, 1) // p3
847 ( 0, 1) // p4
848 ( 1, 1) // p5
849 ( 1, 0) // p6
850 ( 1, -1) // p7
851 ( 0, -1) // p8
852 (-1, -1) |] // p9
853
854 use mat' = new Matrix<byte>(mat.Size)
855 let w = mat'.Width
856 let h = mat'.Height
857 mat.CopyTo(mat')
858
859 let data = mat.Data
860 let data' = mat'.Data
861
862 for i in 0..h-1 do
863 for j in 0..w-1 do
864 if data'.[i, j] = 1uy
865 then
866 let neighborhood = List<Point>()
867 let neighborsToCheck = Stack<Point>()
868 neighborsToCheck.Push(Point(j, i))
869 data'.[i, j] <- 0uy
870
871 while neighborsToCheck.Count > 0 do
872 let n = neighborsToCheck.Pop()
873 neighborhood.Add(n)
874 for (ni, nj) in neighbors do
875 let pi = n.Y + ni
876 let pj = n.X + nj
877 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
878 then
879 neighborsToCheck.Push(Point(pj, pi))
880 data'.[pi, pj] <- 0uy
881 if neighborhood.Count <= areaSize
882 then
883 for n in neighborhood do
884 data.[n.Y, n.X] <- 0uy
885
886 let connectedComponents (img: Image<Gray, byte>) (startPoints: List<Point>) : List<Point> =
887 let w = img.Width
888 let h = img.Height
889
890 let pointChecked = Points()
891 let pointToCheck = Stack<Point>(startPoints);
892
893 let data = img.Data
894
895 while pointToCheck.Count > 0 do
896 let next = pointToCheck.Pop()
897 pointChecked.Add(next) |> ignore
898 for ny in -1 .. 1 do
899 for nx in -1 .. 1 do
900 if ny <> 0 && nx <> 0
901 then
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)
904 then
905 pointToCheck.Push(p)
906
907 List<Point>(pointChecked)
908
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);
911
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);
914
915 let drawEllipse (img: Image<'TColor, 'TDepth>) (e: Types.Ellipse) (color: 'TColor) (alpha: float) =
916 if alpha >= 1.0
917 then
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)
919 else
920 let windowPosX = e.Cx - e.A - 5.f
921 let gapX = windowPosX - (float32 (int windowPosX))
922
923 let windowPosY = e.Cy - e.A - 5.f
924 let gapY = windowPosY - (float32 (int windowPosY))
925
926 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e.A + 5.f) |> int, 2.f * (e.A + 5.f) |> int)
927
928 img.ROI <- roi
929 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
930 then
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
935
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
938
939 let rngCell = System.Random()
940 let drawCell (img: Image<Bgr, byte>) (drawCellContent: bool) (c: Types.Cell) =
941 if drawCellContent
942 then
943 let colorB = rngCell.Next(20, 70)
944 let colorG = rngCell.Next(20, 70)
945 let colorR = rngCell.Next(20, 70)
946
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
950 then
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)
958
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.)
964
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
967
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
970
971
972 let drawCells (img: Image<Bgr, byte>) (drawCellContent: bool) (cells: Types.Cell list) =
973 List.iter (fun c -> drawCell img drawCellContent c) cells