Cleaning + renaming.
[master-thesis.git] / Parasitemia / ParasitemiaCore / ParasitesMarker.fs
1 module ParasitemiaCore.ParasitesMarker
2
3 open System.Drawing
4 open System.Linq
5
6 open Emgu.CV
7 open Emgu.CV.Structure
8
9 open Utils
10 open ImgTools
11
12 type Result = {
13 darkStain: Image<Gray, byte> // Colored pixel, it's independent of the size of the areas. It corresponds to white cells, schizontes, gametocytes, throphozoites.
14 nucleus: Image<Gray, byte> // Parasite nucleus. It may contain some debris. It shouldn't contain thrombocytes or larger elements.
15 parasite: Image<Gray, byte> } // The whole parasites.
16
17 let find (img: Image<Gray, float32>) (config: Config.Config) : Result * Image<Gray, float32> * Image<Gray, float32> =
18
19 let imgWithoutNucleus = img.Copy()
20 areaCloseF imgWithoutNucleus (roundInt config.RBCRadius.NucleusArea)
21
22 let darkStain =
23 // We use the filtered image to find the dark stain.
24 let _, mean_fg, mean_bg =
25 let hist = histogramImg imgWithoutNucleus 300
26 otsu hist
27 imgWithoutNucleus.Cmp(-(float mean_bg) * config.Parameters.darkStainLevel + (float mean_fg), CvEnum.CmpType.LessThan)
28
29 let marker (img: Image<Gray, float32>) (closed: Image<Gray, float32>) (level: float) : Image<Gray, byte> =
30 let diff = img.Copy()
31 diff._Mul(level)
32 CvInvoke.Subtract(closed, diff, diff)
33 diff._ThresholdBinary(Gray(0.0), Gray(255.))
34 diff.Convert<Gray, byte>()
35
36 let nucleusMarker = marker img imgWithoutNucleus (1. / config.Parameters.infectionSensitivity)
37
38 let imgWithoutParasite = img.CopyBlank()
39 let kernelSize =
40 let size = roundInt (config.RBCRadius.Pixel / 5.f)
41 if size % 2 = 0 then size + 1 else size
42 use kernel =
43 if kernelSize <= 3
44 then
45 CvInvoke.GetStructuringElement(CvEnum.ElementShape.Rectangle, Size(3, 3), Point(-1, -1))
46 else
47 CvInvoke.GetStructuringElement(CvEnum.ElementShape.Ellipse, Size(kernelSize, kernelSize), Point(-1, -1))
48
49 CvInvoke.MorphologyEx(img, imgWithoutParasite, CvEnum.MorphOp.Close, kernel, Point(-1, -1), 1, CvEnum.BorderType.Replicate, MCvScalar())
50 let parasiteMarker = marker img imgWithoutParasite (1. / config.Parameters.cytoplasmSensitivity)
51
52 { darkStain = darkStain
53 nucleus = nucleusMarker
54 parasite = parasiteMarker },
55 imgWithoutParasite,
56 imgWithoutNucleus
57
58