* Try another approach to remove false ellipses without success (commented).
[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
35 type Histogram = { data: int[]; total: int; sum: int; min: float32; max: float32 }
36
37 let histogramImg (img: Image<Gray, float32>) (nbSamples: int) : Histogram =
38 let imgData = img.Data
39
40 let min, max =
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]
47
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
51
52 let data = Array.zeroCreate nbSamples
53
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
58
59 { data = data; total = img.Height * img.Width; sum = Array.sum data; min = min; max = max }
60
61 let histogramMat (mat: Matrix<float32>) (nbSamples: int) : Histogram =
62 let matData = mat.Data
63
64 let min, max =
65 let min = ref 0.0
66 let minLocation = ref <| Point()
67 let max = ref 0.0
68 let maxLocation = ref <| Point()
69 mat.MinMax(min, max, minLocation, maxLocation)
70 float32 !min, float32 !max
71
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
75
76 let data = Array.zeroCreate nbSamples
77
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
82
83 { data = data; total = mat.Height * mat.Width; sum = Array.sum data; min = min; max = max }
84
85 let histogram (values: float32 seq) (nbSamples: int) : Histogram =
86 let mutable min = Single.MaxValue
87 let mutable max = Single.MinValue
88 let mutable n = 0
89
90 for v in values do
91 n <- n + 1
92 if v < min then min <- v
93 if v > max then max <- v
94
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
98
99 let data = Array.zeroCreate nbSamples
100
101 for v in values do
102 let p = bin v
103 data.[p] <- data.[p] + 1
104
105 { data = data; total = n; sum = Array.sum data; min = min; max = max }
106
107 let otsu (hist: Histogram) : float32 * float32 * float32 =
108 let mutable sumB = 0
109 let mutable wB = 0
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
113
114 for i in 0 .. hist.data.Length - 1 do
115 wB <- wB + hist.data.[i]
116 if wB <> 0
117 then
118 let wF = hist.total - wB
119 if wF <> 0
120 then
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
126 then
127 level <- i
128 maximum <- between
129
130 let mean1 =
131 let mutable sum = 0
132 let mutable nb = 0
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)
137
138 let mean2 =
139 let mutable sum = 0
140 let mutable nb = 0
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)
145
146 let toFloat l =
147 float32 l / float32 hist.data.Length * (hist.max - hist.min) + hist.min
148
149 toFloat level, toFloat mean1, toFloat mean2
150
151
152 let suppressMConnections (img: Matrix<byte>) =
153 let w = img.Width
154 let h = img.Height
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)
158 then
159 img.[i, j] <- 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)
163 then
164 img.[i, j] <- 0uy
165
166
167 let findEdges (img: Image<Gray, float32>) : Matrix<byte> * Image<Gray, float32> * Image<Gray, float32> =
168 let w = img.Width
169 let h = img.Height
170
171 use sobelKernel =
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))
175
176 let xGradient = img.Convolution(sobelKernel)
177 let yGradient = img.Convolution(sobelKernel.Transpose())
178
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
186
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
192
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).
196
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)
203
204 threshold + (sensibilityHigh * threshold), threshold - (sensibilityLow * threshold)
205
206 // Non-maximum suppression.
207 use nms = new Matrix<byte>(xGradient.Size)
208
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
214
215 let PI = float32 Math.PI
216
217 for i in 0 .. h - 1 do
218 nmsData.[i, 0] <- 0uy
219 nmsData.[i, w - 1] <- 0uy
220
221 for j in 0 .. w - 1 do
222 nmsData.[0, j] <- 0uy
223 nmsData.[h - 1, j] <- 0uy
224
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
230 then
231 let angle = anglesData.[i, j]
232
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
236
237 let mNeigbors (sign: int) : float32 =
238 if angle < PI / 4.f
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]
244 elif angle < PI
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]
253
254 let m = magnitudesData.[i, j]
255 if m >= thresholdLow && m > mNeigbors 1 && m > mNeigbors -1
256 then
257 nmsData.[i, j] <- 1uy
258
259 // suppressMConnections nms // It's not helpful for the rest of the process (ellipse detection).
260
261 let edges = new Matrix<byte>(xGradient.Size)
262 let edgesData = edges.Data
263
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
269 then
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
275 for i' in -1 .. 1 do
276 for j' in -1 .. 1 do
277 if i' <> 0 || j' <> 0
278 then
279 let ni = p.Y + i'
280 let nj = p.X + j'
281 if ni >= 0 && ni < h && nj >= 0 && nj < w && nmsData.[ni, nj] = 1uy
282 then
283 nmsData.[ni, nj] <- 0uy
284 toVisit.Push(Point(nj, ni))
285
286 edges, xGradient, yGradient
287
288
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)
292
293
294 type Points = HashSet<Point>
295
296 let drawPoints (img: Image<Gray, 'TDepth>) (points: Points) (intensity: 'TDepth) =
297 for p in points do
298 img.Data.[p.Y, p.X, 0] <- intensity
299
300 type ExtremumType =
301 | Maxima = 1
302 | Minima = 2
303
304 let findExtremum (img: Image<Gray, 'TDepth>) (extremumType: ExtremumType) : IEnumerable<Points> =
305 let w = img.Width
306 let h = img.Height
307 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
308
309 let imgData = img.Data
310 let suppress: bool[,] = Array2D.zeroCreate h w
311
312 let result = List<List<Point>>()
313
314 let flood (start: Point) : List<List<Point>> =
315 let sameLevelToCheck = Stack<Point>()
316 let betterLevelToCheck = Stack<Point>()
317 betterLevelToCheck.Push(start)
318
319 let result' = List<List<Point>>()
320
321 while betterLevelToCheck.Count > 0 do
322 let p = betterLevelToCheck.Pop()
323 if not suppress.[p.Y, p.X]
324 then
325 suppress.[p.Y, p.X] <- true
326 sameLevelToCheck.Push(p)
327 let current = List<Point>()
328
329 let mutable betterExists = false
330
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
335 for i, j in se do
336 let ni = i + p'.Y
337 let nj = j + p'.X
338 if ni >= 0 && ni < h && nj >= 0 && nj < w
339 then
340 let level = imgData.[ni, nj, 0]
341 let notSuppressed = not suppress.[ni, nj]
342
343 if level = currentLevel && notSuppressed
344 then
345 suppress.[ni, nj] <- true
346 sameLevelToCheck.Push(Point(nj, ni))
347 elif if extremumType = ExtremumType.Maxima then level > currentLevel else level < currentLevel
348 then
349 betterExists <- true
350 if notSuppressed
351 then
352 betterLevelToCheck.Push(Point(nj, ni))
353
354 if not betterExists
355 then
356 result'.Add(current)
357 result'
358
359 for i in 0 .. h - 1 do
360 for j in 0 .. w - 1 do
361 let maxima = flood (Point(j, i))
362 if maxima.Count > 0
363 then
364 result.AddRange(maxima)
365
366 result.Select(fun l -> Points(l))
367
368
369 let findMaxima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
370 findExtremum img ExtremumType.Maxima
371
372
373 let findMinima (img: Image<Gray, 'TDepth>) : IEnumerable<Points> =
374 findExtremum img ExtremumType.Minima
375
376
377 type PriorityQueue () =
378 let size = 256
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
382
383 member this.NextMax () : byte * Point =
384 if this.IsEmpty
385 then
386 invalidOp "Queue is empty"
387 else
388 let l = q.[highest]
389 let next = l.First()
390 l.Remove(next) |> ignore
391 let value = byte highest
392
393 if l.Count = 0
394 then
395 highest <- highest - 1
396 while highest > lowest && q.[highest].Count = 0 do
397 highest <- highest - 1
398 if highest = lowest
399 then
400 highest <- -1
401 lowest <- size
402
403 value, next
404
405 member this.NextMin () : byte * Point =
406 if this.IsEmpty
407 then
408 invalidOp "Queue is empty"
409 else
410 let l = q.[lowest + 1]
411 let next = l.First()
412 l.Remove(next) |> ignore
413 let value = byte (lowest + 1)
414
415 if l.Count = 0
416 then
417 lowest <- lowest + 1
418 while lowest < highest && q.[lowest + 1].Count = 0 do
419 lowest <- lowest + 1
420 if highest = lowest
421 then
422 highest <- -1
423 lowest <- size
424
425 value, next
426
427 member this.Max =
428 highest |> byte
429
430 member this.Min =
431 lowest + 1 |> byte
432
433 member this.Add (value: byte) (p: Point) =
434 let vi = int value
435
436 if vi > highest
437 then
438 highest <- vi
439 if vi <= lowest
440 then
441 lowest <- vi - 1
442
443 q.[vi].Add(p) |> ignore
444
445 member this.Remove (value: byte) (p: Point) =
446 let vi = int value
447 if q.[vi].Remove(p) && q.[vi].Count = 0
448 then
449 if vi = highest
450 then
451 highest <- highest - 1
452 while highest > lowest && q.[highest].Count = 0 do
453 highest <- highest - 1
454 elif vi - 1 = lowest
455 then
456 lowest <- lowest + 1
457 while lowest < highest && q.[lowest + 1].Count = 0 do
458 lowest <- lowest + 1
459
460 if highest = lowest // The queue is now empty.
461 then
462 highest <- -1
463 lowest <- size
464
465 member this.IsEmpty =
466 highest = -1
467
468 member this.Clear () =
469 while highest > lowest do
470 q.[highest].Clear()
471 highest <- highest - 1
472 highest <- -1
473 lowest <- size
474
475
476 type private AreaState =
477 | Removed = 1
478 | Unprocessed = 2
479 | Validated = 3
480
481 type private AreaOperation =
482 | Opening = 1
483 | Closing = 2
484
485 [<AllowNullLiteral>]
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
490
491 let private areaOperation (img: Image<Gray, byte>) (area: int) (op: AreaOperation) =
492 let w = img.Width
493 let h = img.Height
494 let imgData = img.Data
495 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
496
497 let areas = List<Area>((if op = AreaOperation.Opening then findMaxima img else findMinima img) |> Seq.map Area)
498
499 let pixels: Area[,] = Array2D.create h w null
500 for m in areas do
501 for e in m.Elements do
502 pixels.[e.Y, e.X] <- m
503
504 let queue = PriorityQueue()
505
506 let addEdgeToQueue (elements: Points) =
507 for p in elements do
508 for i, j in se do
509 let ni = i + p.Y
510 let nj = j + p.X
511 let p' = Point(nj, ni)
512 if ni >= 0 && ni < h && nj >= 0 && nj < w && not (elements.Contains(p'))
513 then
514 queue.Add (imgData.[ni, nj, 0]) p'
515
516 // Reverse order is quicker.
517 for i in areas.Count - 1 .. -1 .. 0 do
518 let m = areas.[i]
519 if m.Elements.Count <= area && m.State <> AreaState.Removed
520 then
521 queue.Clear()
522 addEdgeToQueue m.Elements
523
524 let mutable intensity = if op = AreaOperation.Opening then queue.Max else queue.Min
525 let nextElements = Points()
526
527 let mutable stop = false
528 while not stop do
529 let intensity', p = if op = AreaOperation.Opening then queue.NextMax () else queue.NextMin ()
530 let mutable merged = false
531
532 if intensity' = intensity // The intensity doesn't change.
533 then
534 if m.Elements.Count + nextElements.Count + 1 > area
535 then
536 m.State <- AreaState.Validated
537 m.Intensity <- Some intensity
538 stop <- true
539 else
540 nextElements.Add(p) |> ignore
541
542 elif if op = AreaOperation.Opening then intensity' < intensity else intensity' > intensity
543 then
544 m.Elements.UnionWith(nextElements)
545 for e in nextElements do
546 pixels.[e.Y, e.X] <- m
547
548 if m.Elements.Count = area
549 then
550 m.State <- AreaState.Validated
551 m.Intensity <- Some (intensity')
552 stop <- true
553 else
554 intensity <- intensity'
555 nextElements.Clear()
556 nextElements.Add(p) |> ignore
557
558 else
559 let m' = pixels.[p.Y, p.X]
560 if m' <> null
561 then
562 if m'.Elements.Count + m.Elements.Count <= area
563 then
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
572 then
573 intensity <- intensityMax
574 nextElements.Clear()
575 merged <- true
576
577 if not merged
578 then
579 m.State <- AreaState.Validated
580 m.Intensity <- Some (intensity)
581 stop <- true
582
583 if not stop && not merged
584 then
585 for i, j in se do
586 let ni = i + p.Y
587 let nj = j + p.X
588 let p' = Point(nj, ni)
589 if ni < 0 || ni >= h || nj < 0 || nj >= w
590 then
591 m.State <- AreaState.Validated
592 m.Intensity <- Some (intensity)
593 stop <- true
594 elif not (m.Elements.Contains(p')) && not (nextElements.Contains(p'))
595 then
596 queue.Add (imgData.[ni, nj, 0]) p'
597
598 if queue.IsEmpty
599 then
600 if m.Elements.Count + nextElements.Count <= area
601 then
602 m.State <- AreaState.Validated
603 m.Intensity <- Some intensity'
604 m.Elements.UnionWith(nextElements)
605 stop <- true
606
607 for m in areas do
608 if m.State = AreaState.Validated
609 then
610 match m.Intensity with
611 | Some i ->
612 for p in m.Elements do
613 imgData.[p.Y, p.X, 0] <- i
614 | _ -> ()
615 ()
616
617
618 let areaOpen (img: Image<Gray, byte>) (area: int) =
619 areaOperation img area AreaOperation.Opening
620
621 let areaClose (img: Image<Gray, byte>) (area: int) =
622 areaOperation img area AreaOperation.Closing
623
624 [<AllowNullLiteral>]
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
629
630
631 let private areaOperationF (img: Image<Gray, float32>) (area: int) (op: AreaOperation) =
632 let w = img.Width
633 let h = img.Height
634 let earth = img.Data
635 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
636
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) }
640
641 let ownership: Island[,] = Array2D.create h w null
642
643 // Initialize islands with their shore.
644 let islands = List<Island>()
645 let extremum = img |> if op = AreaOperation.Opening then findMaxima else findMinima
646 for e in extremum do
647 let island =
648 let p = e.First()
649 Island(comparer, Level = earth.[p.Y, p.X, 0], Surface = e.Count)
650 islands.Add(island)
651 let shorePoints = Points()
652 for p in e do
653 ownership.[p.Y, p.X] <- island
654 for i, j in se do
655 let ni = i + p.Y
656 let nj = j + p.X
657 let neighbor = Point(nj, ni)
658 if ni >= 0 && ni < h && nj >= 0 && nj < w && ownership.[ni, nj] = null && not (shorePoints.Contains(neighbor))
659 then
660 shorePoints.Add(neighbor) |> ignore
661 island.Shore.Add earth.[ni, nj, 0] neighbor
662
663 for island in islands do
664 let mutable stop = island.Shore.IsEmpty
665
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)
673
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.
678 then
679 island.Shore.RemoveNext ()
680 else
681 if other <> null
682 then // We touching another island.
683 if island.Surface + other.Surface >= area
684 then
685 stop <- true
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
694 island.Shore.Add l p
695 other.Shore.Clear()
696
697 elif comparer.Compare(level, island.Level) > 0
698 then
699 stop <- true
700 else
701 island.Shore.RemoveNext ()
702 for i, j in se do
703 let ni = i + next.Y
704 let nj = j + next.X
705 if ni < 0 || ni >= h || nj < 0 || nj >= w
706 then
707 island.Surface <- Int32.MaxValue
708 stop <- true
709 else
710 let neighbor = Point(nj, ni)
711 if not <| ownedOrAdjacent neighbor
712 then
713 island.Shore.Add earth.[ni, nj, 0] neighbor
714 if not stop
715 then
716 ownership.[next.Y, next.X] <- island
717 island.Level <- level
718 island.Surface <- island.Surface + 1
719
720 for i in 0 .. h - 1 do
721 for j in 0 .. w - 1 do
722 let island = ownership.[i, j]
723 if island <> null
724 then
725 earth.[i, j, 0] <- island.Level
726 ()
727
728
729 let areaOpenF (img: Image<Gray, float32>) (area: int) =
730 areaOperationF img area AreaOperation.Opening
731
732 let areaCloseF (img: Image<Gray, float32>) (area: int) =
733 areaOperationF img area AreaOperation.Closing
734
735 // A simpler algorithm than 'areaOpen' but slower.
736 let areaOpen2 (img: Image<Gray, byte>) (area: int) =
737 let w = img.Width
738 let h = img.Height
739 let imgData = img.Data
740 let se = [| -1, 0; 0, -1; 1, 0; 0, 1 |]
741
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
747
748 let flooded : bool[,] = Array2D.zeroCreate h w
749
750 let pointsChecked = HashSet<Point>()
751 let pointsToCheck = Stack<Point>()
752
753 for level in 255 .. -1 .. 0 do
754 let mutable n = histogram.[level]
755 if n > 0
756 then
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
760 then
761 let mutable maxNeighborValue = 0uy
762 pointsChecked.Clear()
763 pointsToCheck.Clear()
764 pointsToCheck.Push(Point(j, i))
765
766 while pointsToCheck.Count > 0 do
767 let next = pointsToCheck.Pop()
768 pointsChecked.Add(next) |> ignore
769 flooded.[next.Y, next.X] <- true
770
771 for nx, ny in se do
772 let p = Point(next.X + nx, next.Y + ny)
773 if p.X >= 0 && p.X < w && p.Y >= 0 && p.Y < h
774 then
775 let v = imgData.[p.Y, p.X, 0]
776 if v = byte level
777 then
778 if not (pointsChecked.Contains(p))
779 then
780 pointsToCheck.Push(p)
781 elif v > maxNeighborValue
782 then
783 maxNeighborValue <- v
784
785 if int maxNeighborValue < level && pointsChecked.Count <= area
786 then
787 for p in pointsChecked do
788 imgData.[p.Y, p.X, 0] <- maxNeighborValue
789
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
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) =
845 let neighbors = [|
846 (-1, 0) // p2
847 (-1, 1) // p3
848 ( 0, 1) // p4
849 ( 1, 1) // p5
850 ( 1, 0) // p6
851 ( 1, -1) // p7
852 ( 0, -1) // p8
853 (-1, -1) |] // p9
854
855 use mat' = new Matrix<byte>(mat.Size)
856 let w = mat'.Width
857 let h = mat'.Height
858 mat.CopyTo(mat')
859
860 let data = mat.Data
861 let data' = mat'.Data
862
863 for i in 0..h-1 do
864 for j in 0..w-1 do
865 if data'.[i, j] = 1uy
866 then
867 let neighborhood = List<Point>()
868 let neighborsToCheck = Stack<Point>()
869 neighborsToCheck.Push(Point(j, i))
870 data'.[i, j] <- 0uy
871
872 while neighborsToCheck.Count > 0 do
873 let n = neighborsToCheck.Pop()
874 neighborhood.Add(n)
875 for (ni, nj) in neighbors do
876 let pi = n.Y + ni
877 let pj = n.X + nj
878 if pi >= 0 && pi < h && pj >= 0 && pj < w && data'.[pi, pj] = 1uy
879 then
880 neighborsToCheck.Push(Point(pj, pi))
881 data'.[pi, pj] <- 0uy
882 if neighborhood.Count <= areaSize
883 then
884 for n in neighborhood do
885 data.[n.Y, n.X] <- 0uy
886
887 let connectedComponents (img: Image<Gray, byte>) (startPoints: List<Point>) : List<Point> =
888 let w = img.Width
889 let h = img.Height
890
891 let pointChecked = Points()
892 let pointToCheck = Stack<Point>(startPoints);
893
894 let data = img.Data
895
896 while pointToCheck.Count > 0 do
897 let next = pointToCheck.Pop()
898 pointChecked.Add(next) |> ignore
899 for ny in -1 .. 1 do
900 for nx in -1 .. 1 do
901 if ny <> 0 && nx <> 0
902 then
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)
905 then
906 pointToCheck.Push(p)
907
908 List<Point>(pointChecked)
909
910
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);
913
914
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);
917
918
919 let drawEllipse (img: Image<'TColor, 'TDepth>) (e: Types.Ellipse) (color: 'TColor) (alpha: float) =
920
921 if alpha >= 1.0
922 then
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)
924 else
925 let windowPosX = e.Cx - e.A - 5.f
926 let gapX = windowPosX - (float32 (int windowPosX))
927
928 let windowPosY = e.Cy - e.A - 5.f
929 let gapY = windowPosY - (float32 (int windowPosY))
930
931 let roi = Rectangle(int windowPosX, int windowPosY, 2.f * (e.A + 5.f) |> int, 2.f * (e.A + 5.f) |> int)
932
933 img.ROI <- roi
934 if roi = img.ROI // We do not display ellipses touching the edges (FIXME)
935 then
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
940
941
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
944
945
946 let rngCell = System.Random()
947 let drawCell (img: Image<Bgr, byte>) (drawCellContent: bool) (c: Types.Cell) =
948 if drawCellContent
949 then
950 let colorB = rngCell.Next(20, 70)
951 let colorG = rngCell.Next(20, 70)
952 let colorR = rngCell.Next(20, 70)
953
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
957 then
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)
965
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.)
971
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
974
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
977
978
979 let drawCells (img: Image<Bgr, byte>) (drawCellContent: bool) (cells: Types.Cell list) =
980 List.iter (fun c -> drawCell img drawCellContent c) cells