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